How to pass Variable from External JavaScript to H

2019-09-21 16:21发布

问题:

I have been trying to pass a value from an external javascript file to an HTML form with no luck. The files are rather large so I am not sure I can explain it all but ill try.

Basically a user clicks a link then a js file is initiated. Immediately after a new HTML page loads.

I need this value passed to the HTML page in a form field.

Javascript:

var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };

document.getElementById('adcode').value = divElement(); 

Afterwards it should be passed to this Form field

HTML Form Field:

<p>Ad Code:<br>
<input type="text" name="adcode" id="adcode"/>

  <br>
  </p>

Thanks for any help!

回答1:

Your HTML file needs to reference the JavaScript js file. Have a function in your JavaScript that returns the value that you need. Use JavaScript (I like jQuery) to set the form field to what you need.

JS file:

<script>
  var divElement = function(){
  divCode = document.getElementById(div1).innerHTML;
  return divCode; };

  document.getElementById('adcode').value = divElement(); 

  function GetDivElement() {
    return divElement();
  }
</script>

HTML file:

<p>Ad Code:
  <br />
  <input type="text" name="adcode" id="adcode"/>
  <br />
</p>

<script src="wherever that js file is" />
<script>
  window.onload = function() {
      document.getElementById('adcode').value = GetDivElement();
  }
</script>

Although, really, this might do what you want (depending on what you are trying to do):

<p>Ad Code:
  <br />
  <input type="text" name="adcode" id="adcode"/>
  <br />
</p>

<script src="wherever that js file is" />
<script>
  window.onload = function() {
      GetDivElement();
  }
</script>


回答2:

Can it be this?:

function divElement(divCode){
return divCode; 
}

divElement(document.getElementById('adcode').value);