1

我在这个 div 之前添加了一些带有内容的元素

<div id="before_this">
  blablabla
</div>

我的js:

$('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this').find('.comment');

但类comment属性不会应用于新添加的元素。

我怎样才能在 jquery 中实现这一点?

4

3 回答 3

2

insertBefore返回调用它的集合。您的示例中的这个集合已经是p.comment.

在控制台中试试这个,你会看到p.commentjQuery 对象:

var $p = $('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this');

console.log($p); // p.comment jQ object
于 2013-05-25T23:23:24.393 回答
2

那个怎么样?它已应用<p>,因为您使用 class创建了一个新元素.comment。但是.find()不会起作用,因为没有<p>具有 class的后代.comment

如果您需要使用插入的元素,请继续使用链接:

$("<p class='comment'>...</p>").insertBefore("#before_this").css("color", "red");
于 2013-05-25T23:23:38.393 回答
1

最后.find()的 寻找被选元素内的元素。由于您要查找的元素是选定元素,因此这将永远不会起作用。(换句话说,没有p.comment具有“评论”类的后代。)

如果您要做的是选择刚刚创建的元素,则它已经被选中。

var selectedElement = $('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this');
// selectedElement === $('p.comment');

如果您想要类名,请改用以下内容:

$('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this').attr('class');

但是这当然没有任何意义,因为您已经知道您创建的元素的类并赋予“评论”类将是“评论”!

于 2013-05-25T23:23:37.133 回答