添加选择器时出现.load()问题

时间:2014-08-21 15:59:00

标签: javascript jquery

我在点击事件后加载html然后在新元素上执行动画时遇到问题。当我在加载调用中添加选择器后缀时,html不会加载,但事件处理程序返回"成功。"没有选择器附加html加载,但我无法用jquery选择它。

HTML:

<button id="btn-click">Click me</button>
<div id="placeholder"></div>

JS:

$("#btn-click").click( function () {
    $("#placeholder").load("dynamicContent.html #new-content", function () {
        $("#new-content").css( "color", "red");
    });
});

dynamicContent.html

<p>just some text for now.</p>

这根本不会加载新文件。是否有可能发生这种情况?

2 个答案:

答案 0 :(得分:1)

如果我了解您,您希望加载新内容,然后对该内容执行某些操作。它可能会这样工作:

("#btn-click").click( function () {
    $("#placeholder").load("dynamicContent.html", function () {
        $(this).find("#new-content").css( "color", "red");
        //or: $("#new-content", this).css( "color", "red");
    });
});

根据jQuery doc:“如果提供了”完整“回调,则会在后处理和执行HTML插入后执行。”因此,在完整功能中,您应该能够使用上述内容或$("#new-content", this)

访问新内容

<强>更新

重新阅读问题时,如果要更改加载的HTML中<p>的颜色,请转到$("p", this).css( "color", "red");

如果要更改整个占位符的颜色,请使用:$(this).css( "color", "red");

答案 1 :(得分:1)

正如我在评论中所解释的那样,您尝试加载的内容没有ID为new-content的元素,因此无需为jQuery加载任何内容。

您的新内容包含p元素,因此如果您想定位该内容,只需.find

$("#btn-click").click( function () {
    $("#placeholder").load("dynamicContent.html", function () {
        $(this).find('p').css( "color", "red");
    });
});

.load回调中,this引用所选元素,您可以使用任何traversal method来查找要操作的元素。