【问题标题】:Where does my dynamically added script go?我动态添加的脚本去哪里了?
【发布时间】:2012-12-18 14:45:23
【问题描述】:

我是 Web 开发的新手,我正在尝试了解 DOM 的工作原理。

我有一个带有 2 个按钮和一些文本的基本页面。其中一个按钮调用 Jquery 的 Get 函数。我的服务器也返回了一些带有一些脚本的 html。然后将其添加到我的主页上的我的DIV 中,该主页具有“内容”的ID

代码见下文。

主页

<!DOCTYPE html>
<link rel="stylesheet" href="css/toastr.css">  
<html> 
<body>

<h1>My Main Page </h1>


<button class="alertmsg">click me</button>
<button class="addDom" >Call Add HTML</button>

<div id="content">
</div>

</body>
</html>

<script src="js/jquery.js"></script>
<script src="js/toastr.js"></script>
<script>
$(document).ready(function(){

$(".alertmsg").click(function() {
alert("Hello World!");
});

$(".addDom").click(function(){
$.get( '/adddom',
 function (data) {
        // put html into the section
        $("div#content").html(data);
    })
});

});
</script>

代码返回

<div>
<h1>Added Via $.html</h1>
<button class="showmsg">click me for jquery</button>
</div>

<script>
$(document).ready(function(){
$(".showmsg").click(function(){
toastr.warning( "Test Warning", 'Warning');
});

});
</script>

更新的 DOM - 请注意我的新 javascript 未显示。

<!DOCTYPE html>
<link rel="stylesheet" href="css/toastr.css">  
<html> 
<body>

<h1>My Main Page </h1>


<button class="alertmsg">click me</button>
<button class="addDom" >Call Add HTML</button>

<div id="content">
  <div>
   <h1>Added Via $.html</h1>
   <button class="showmsg">click me for jquery</button>
   </div>  
</div>
</body>
</html>

<script src="js/jquery.js"></script>
<script src="js/toastr.js"></script>
<script>
$(document).ready(function(){

$(".alertmsg").click(function() {
alert("Hello World!");
});

$(".addDom").click(function(){
$.get( '/adddom',
 function (data) {
        // put html into the section
        $("div#content").html(data);
    })
});
});
</script>

我想了解的是;

1) 我的新脚本代码在哪里?

<script>
$(document).ready(function(){
   $(".showmsg").click(function(){
   toastr.warning( "Test Warning", 'Warning');
  });
});
</script>

它只在内存中而不是在 DOM 中吗?

2) 我可以正确显示警告,即$(".showmsg").click 触发并显示预期的内容。所以我的脚本可以引用 DOM 中需要的现有库。这是如何工作的?

3) 如果我在浏览器中看不到此代码,最好的解决方法是什么?

非常感谢!

【问题讨论】:

    标签: html jquery dom html-parsing


    【解决方案1】:

    如果你真的想将脚本附加到 dom 你需要使用appendChild() 而不是.html()link about appendChild

    这样做的一个例子是

    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.text = 'alert("test");';
    $('div')[0].appendChild(script);
    

    这是一个fiddle 显示这个。

    【讨论】:

    • 谢谢布莱克。我会试试的。但是我想我正在尝试了解这一切是如何运作的。我使用的方法有效,即事件处理工作正常,我只是想了解它是如何组合在一起的。
    • @user1768233 查看此question 以获得很好的解释。
    • 谢谢布莱克。这就是我所追求的:)
    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多