Javascript 将带有脚本标记的HTML文件动态注入页面

Javascript 将带有脚本标记的HTML文件动态注入页面,javascript,jquery,Javascript,Jquery,我有一个主页,index.htm,它动态注入html文件 这个很好用。但是,如果我在同一个页面上附加两次component.htm,该如何解决这个问题呢?第二次添加组件html时,$('.foo')选择器将返回两个元素 如何使它找到属于该实例的相应“container”元素?我想$('.foo:last')可以,但一定有更好的解决方案,对吗 component.htm: <script> $(function(){ var $div = $('.foo');

我有一个主页,
index.htm
,它动态注入html文件

这个很好用。但是,如果我在同一个页面上附加两次
component.htm
,该如何解决这个问题呢?第二次添加组件html时,
$('.foo')
选择器将返回两个元素

如何使它找到属于该实例的相应“container”元素?我想
$('.foo:last')
可以,但一定有更好的解决方案,对吗

component.htm:

<script>
    $(function(){
        var $div = $('.foo');
    });
</script>
<div class="foo"></div>

您可以为放置在
component.htm
中的每个节点提供
id
。这样你就能确切地知道你指的是哪个“容器”。之后,您只需更改选择器以在相应节点内查找
.foo

component.htm

<script>
    $(function(){
        var $firstDiv = $('#first > .foo');
        var $secondDiv = $('#second > .foo');
    });
</script>
<div class="foo"></div>
$.ajax({
    url: 'component.htm',
    dataType: 'html'
}).done(function(html){
    $('body #first').append(html);
    $('body #second').append(html); //not sure exactly where you want this,
                                    //but this is the idea.
});
在HTML中,只需准备好两个容器,即可将HTML放入其中:

<body>
    ...
    <div id="#first"></div>
    <div id="#second"></div>
    ...
</body>

...
...

如果componet.html文件中没有太多代码,那么可以动态添加可选元素,如下所示

component.html

 <script>
$(function(){
    var $div = $('<div class="foo"></div>').
       /*attach or listen to events here*/
       .appendTo('body');
});
</script>

$(函数(){
变量$div=$('')。
/*在此附加或收听事件*/
.附于(“主体”);
});

只需将页面添加到已经命名的组件(如“div1”)中,然后从那里搜索“$”(“div1>.foo”)。@MichaelLaffargue尽管组件html中的脚本不知道使用哪个容器,但不管
$(“div1>.foo”)
$(.foo”)
容器与否,问题仍然存在。组件html中的选择器如何知道其外部容器?选择器从html的根向下工作,因此它是否放在
component.htm
中并不重要。
 <script>
$(function(){
    var $div = $('<div class="foo"></div>').
       /*attach or listen to events here*/
       .appendTo('body');
});
</script>