DOMContentLoaded doesn't work

时间:2015-09-08 10:23:16

标签: javascript

I'm trying to test DOMContentLoaded event, and this code doesn't work for me.

Html

<p id="tst" >Click me</p>
<p id="tst2"> Element 2 </p>

Script

(function(){
    var tst, tst2;

    document.addEventListener("DOMContentLoaded",function(evt){
        tst = document.getElementById("tst");
        tst.innerText = "Element 4";
    });
})();

I only want to see change innerText propertie of html element.

Thanks you all.

Fiddle : https://jsfiddle.net/jastertdc/h1qjqjug/

的图片

2 个答案:

答案 0 :(得分:1)

(function() {
  var tst, tst2;
  document.addEventListener("DOMContentLoaded", function(evt) {
    tst = document.getElementById("tst");
    tst.innerHTML = "Element 4";
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="tst">Click me</p>
<p id="tst2">Element 2</p>

innerText无效,您应该使用

tst.innerHTML = "Element 4";

OR

tst.textContent= "Element 4";

答案 1 :(得分:1)

它运作得很好。但是,您在JSFiddle环境设置中搞砸了它。

在左窗格中,您选择库和扩展名,您已选择onLoad,因为您希望执行脚本。

将其更改为No wrap - in <body>,它可以正常工作。

Here, come take a look.:)

附录::

当您在左侧窗格中选择onLoad时,JSFiddle真棒会生成此代码

<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function(){
    var tst, tst2;
    console.log('test')
    document.addEventListener("DOMContentLoaded",function(evt){
        tst = document.getElementById("tst");
        tst.innerText = "Element 4";
    });
})();
}//]]> 

如您所见,文件中已存在window.onload,将在DOMContentLoaded上执行。在你内心addEventListener DOMContentLoaded之内。因此,当您附加此事件处理程序时,事件已经发生,因此您不会看到您的文本发生变化。

另一方面,

No wrap - in <body>使得真棒生成以下代码

<script type='text/javascript'>//<![CDATA[

(function(){
    var tst, tst2;
    console.log('test');
    document.addEventListener("DOMContentLoaded",function(evt){
        tst = document.getElementById("tst");
        tst.innerText = "Element 4";
    });
})();
//]]> 

</script>

所以,它有效。 ! :)