使用脚本标记将HTML文件动态注入页面

时间:2015-05-27 13:08:09

标签: javascript jquery

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

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

如何让它找到属于该实例的corrent“container”元素?我想$('.foo:last')会起作用,但必须有更好的解决方案,对吗?

component.htm:

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

来自 index.htm

$.ajax({
    url: 'component.htm',
    dataType: 'html'
}).done(function(html){
    $('body').append(html);
});

2 个答案:

答案 0 :(得分:0)

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

<强> component.htm

<script>
    $(function(){
        var $firstDiv = $('#first > .foo');
        var $secondDiv = $('#second > .foo');
    });
</script>
<div class="foo"></div>

<强>的index.htm

$.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>

答案 1 :(得分:0)

如果您的componet.html文件中没有很多代码,那么您可以动态添加可选元素,例如

<强> component.html

Traceback (most recent call last)
  self.font = value.font.copy()
AttributeError: 'PatternFill' object has no attribute 'font'