插入之前,发现CSS类- js不工作
insertbefore and find the css class - js not working
我在这个div
之前添加了一些内容元素<div id="before_this">
blablabla
</div>
my js:
$('<p class="comment"> test <small> date </small></p>').insertBefore('#before_this').find('.comment');
,但类comment
属性不会应用于新添加的元素。
如何在jquery中实现这一点?
这是怎么回事?它被应用,因为您创建了一个具有.comment
类的新元素<p>
。但是.find()
不能工作,因为没有<p>
的后代,它们具有.comment
类。
如果您需要处理插入的元素,请继续使用链接:
$("<p class='comment'>...</p>").insertBefore("#before_this").css("color", "red");
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
最后的.find()
在所选元素中查找元素。因为您要查找的元素是选中的元素,所以这永远不会起作用。(换句话说,没有p.comment
的后代具有类"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');
但是这当然没有意义,因为你已经知道你创建的元素的类,并给了一个类"comment"将是"comment"!
相关文章:
- 如何使用多个jquery版本,以便Responsive Slides.js工作
- 无法使FlowType.js工作
- Intellisense没有;t在VS2013中为JS工作
- 有人能解释一下如何#ifeq吗/section键使用handle.js工作
- 使dropzone.js工作的傻瓜指南
- 如何获得侧边栏.js工作
- 如何在没有 Web 服务器的情况下做出响应.js工作
- 创建JS工作,但不显示工具栏
- 无法获得简单的敏捷.js工作
- 通过有错误的 Ajax-Request 打印出 HTML 会阻止进一步的 JS 工作
- Angular JS-工作函数中的“错误:[$interpole:interr]Can't interpole:
- 推特's Bootstrap Popover:赢得't工作,即使其他JS工作正常
- 可以'不要让typeahead.js工作
- 无法让Quicksand.js工作
- 通过Grunt使用Node.js工作SASS预处理器
- 可以'不要让popcorn.js工作
- 不能让Bootstrap modal.js工作
- 我怎么能与wordpress中的wow.min.js工作
- 无法让haxe-pixi.js工作-我得到一个空白的白色屏幕
- 不能让impress.js工作