当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Get element using id problem

问题描述:

I am modifying existing legacy webpages(which i shouldn't modify existing parts but adding) and the webpage uses document.write to write certain html elements. when i use

<script type="text/javascript" language="javascript">

var v = document.getElementById('td_date_cal_0');

alert(v);

</script>

v becomes null and when i create button and click

<input type="button" id="mnbutton" onclick="mnLoader();" value="Click Me!" />;

<script type="text/javascript" language="javascript" >

function mnLoader() {

var v = document.getElementById("td_date_cal_0");

alert(v);

} <br />

</script>

Any idea, how to get the element without need of user action, such as clicking?

Thanks,

Ebe

网友答案:

Try attaching the script to the onload event of either document or window.

function mnLoader() {
 var v = document.getElementById("td_date_cal_0");
 alert(v); 
}
// Execute the function after the page has loaded
document.onload = function() {
 mnLoader();
}
网友答案:

I'm guessing you are placing your script element before the element you are trying to get.

The simplest way to resolve this is to put your script element immediately before the END tag for the body element.

网友答案:

I expect this is happening because at the point the script runs before the element with ID "td_date_cal_0" has been created.

Try moving the script to beneath the element that it is manipulating or wire the code up to the document.onload event.

网友答案:

@Mathias gave an example that will most likely fix your problem. Which is that the element you're trying to access using document.getElementById hasn't been loaded into the DOM yet at the time you're trying it.

However, if you're interested in being able to run your code as early as possible a better solution is to observer the "dom:loaded" event, or DOM ready event. This is a bit more involved than calling window.onload but a framework such as Prototype.js or jQuery can help.

See this page in which Michael Sharman talks about just this very feature.

You can then write code such as:


document.observe(document, 'dom:loaded', initFunction);   

function initFunction()  
{  
  // this code will run as soon as DOM is loaded, 
  // but before any images are loaded
}

Obviously if you don't want to use a framework, you can replicate the behavior using just the standard javascript calls but you will have to be prepared to deal with differences between browsers. You can start by looking at the onreadystatechanged event and the similar events for other browsers (i.e. DOMContentLoaded)

网友答案:

following code work correctly.

<input type="text" id="xxxx"/>
<input type="button" id="mnbutton" onclick="mnLoader();" value="Click Me!" />;
<script>
        function mnLoader() {
        var v = document.getElementById("xxxx").value;
        alert(v); 
        }
</script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: