我在此div之前添加了一些内容元素
<div id="before_this">
blablabla
</div>
我的js:
$('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this').find('.comment');
但是类comment
属性不会应用于新添加的元素。
我怎样才能在jquery中实现这一点?
答案 0 :(得分:2)
insertBefore
返回调用它的集合。您的示例中的此集合已为p.comment
。
在控制台中尝试此操作,您将看到p.comment
jQuery对象:
var $p = $('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this');
console.log($p); // p.comment jQ object
答案 1 :(得分:2)
<p>
创建新元素.comment
。但是.find()
无法使用,因为<p>
没有后代,其中有.comment
类。
如果您需要使用inserted元素,请继续使用链接:
$("<p class='comment'>...</p>").insertBefore("#before_this").css("color", "red");
答案 2 :(得分: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');
但当然这没有任何意义,因为你已经知道你创建的元素的类并给出了一个“注释”类将是“评论”!