开发者

Cannot pass getElementByID object to external JS file on Chrome

开发者 https://www.devze.com 2023-04-12 17:28 出处:网络
I\'ve created a simple JS file, called formValueOperator.js, containing this function: function setValue(type, obj, value){

I've created a simple JS file, called formValueOperator.js, containing this function:

function setValue(type, obj, value){
if(type == 'text')
{
    obj.value = value;
}

and another HTML page calling this function:

<HTML>
   <HEAD>
      <title>Simple Test</title>
      <script type="text/javascript" src="formValueOperator.js"></script>
      <script ty开发者_JAVA技巧pe="text/javascript">
         function setInitValue(){
              var element_order_id = document.getElementById("order_id");
              setValue('text', element_order_id, 'aaa');
         }
      </script>
   </HEAD>
   <BODY>
         <FORM name="myform" method="post">
              <input type="text" size=20 id="order_id" name="order_id">
         </FORM>
         <script type="text/javascript">
              setInitValue();
         </script>
   </BODY>
</HTML>

It's quite a simple operation:

Run HTML --> call function setInitValue() --> put 'aaa' in text box.

Everything work perfectly on FireFox (7.0.1). However, when I tried to run this on Chrome (14.0.835.202), it didn't work at all.

Then, I tested the code by moving entire setValue function from formValueOperator.js and pasted it in HTML page. Surprisingly, it worked.

There must be something fishy about how Chrome pass getElementByID object to external JS file.

Could anyone please help me on this one?


Try in this way, delaying the method execution until the web-pages has been loaded:

<FORM name="myform" method="post">
   <input type="text" size=20 id="order_id" name="order_id" />
</FORM>

<script type="text/javascript">
   window.onload = function() {
      setInitValue();
  };
</script>


It's to do with when the setInitValue() method is fired.

When you move your method outside of the JS file and into the body of the document you're probably delaying the executing of the method a few milliseconds giving the element you're selecting time to load.

Use jQuery's ready event to execute your code when everything has finished loading.

$(document).ready(function(){
  setInitValue();
 }
);
0

精彩评论

暂无评论...
验证码 换一张
取 消