为什么下面的代码不能按预期工作? (用class = clear选择div之前的所有元素?)
HTML:
<div id="text">
line0
<div>line1</div>
<div>line2</div>
<div class="clear" />
<div>dummy</div>
<p>dummy</p>
</div>
JS:
var allow = true;
var output = $('#text *').filter(function(index) {
if( $(this).attr("class") == 'clear') {
allow = false;
}
return allow;
}).html().trim();
alert( output );
输出:
line1
期待: 第0行 第一行 行2
最佳答案
发生这种情况是因为作为 .html()
说
Get the HTML contents of the first element in the set of matched elements.
因此,虽然您的两个 div 都被选中,但只有一个由 .html()
返回
检查这个fiddle验证您的代码是否返回了这两个元素。
正如其他人所说,您应该使用 .hasClass
方法。
更新
那样line0
不在任何节点内,它是一个文本节点,您可以先在文本节点周围循环并添加 span 标签。或者您将无法对该文本应用样式。检查以下代码
var whitespace = /^\s*$/;
$('#text').contents().filter(function(){
return this.nodeType == 3 && !whitespace.test(this.nodeValue);
}).wrap('<span></span>');
这会遍历所有子节点(包括文本节点)并用 span
包裹非空格文本节点.
所以在那之后你的 line0 将在像 <span>line0</span>
这样的跨度标签内.所以现在如果你这样做
$('.clear').prevAll().css('color', 'red');
它将突出显示line0
也是。
检查 Node Types MDN 上的文档
关于javascript - jQuery 过滤器和 html 返回奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11034918/