我正在处理一些生成的跨度,我想找到哪一个不包含任何文本.
标记是:
<span id="layer6">
<span class="drag col"> Some text</span>
<span class="drag col"> More text</span>
<span class="drag col"> </span>
<span class="drag col"> I also have text</span>
</span>
Run Code Online (Sandbox Code Playgroud)
我可以使用此代码获取具有"一些文本"的那些但我无法获得空代码:
if ($('#layer6 > span.col:contains("some text")').length > 0) {
alert ("I have text");
}
Run Code Online (Sandbox Code Playgroud)
如何获得空的?我正在考虑使用.length来做,但我没有管理.
Ale*_*lex 49
$("span.col").each(function(){
if (!$(this).text().trim().length) {
$(this).addClass("foo");
}
});
Run Code Online (Sandbox Code Playgroud)
显然,不是添加一个你可以随意做的类,而是返回对象等
更新:删除导致js错误的最终分号后删除奇怪的隐藏字符.
使用filter过滤没有文本内容的元素:
$('#layer6 > span.col').filter(function(){
return $(this).text().trim() != "";
}).length
Run Code Online (Sandbox Code Playgroud)
我不知道这样的选择器,但它很容易写
jQuery.expr [':'].empty = function(obj){return jQuery(obj).text().replace(/ ^\s + |\s + $ /,"").length == 0; }
jQuery.expr[':'].hasNoText = function(obj) {
return jQuery.trim(jQuery(obj).text()).length == 0;
}
Run Code Online (Sandbox Code Playgroud)
然后,例如
$("#layer6 span:hasNoText").text("NEW TEXT")
Run Code Online (Sandbox Code Playgroud)
只是为了谷歌的利益,这是扩展版本.$("node:matches(/ regexp /)")选择文本内容与给定regexp匹配的节点.
<script>
/// :matches(regexp)
/// regexp is like js regexp except that you should double all slashes
jQuery.expr[':'].matches = function(obj, index, args) {
var m = (args[3] + "").match(/^\/(.+?)\/(\w*)$/);
var re = new RegExp(m[1], m[2]);
return jQuery(obj).text().search(re) >= 0;
}
</script>
Run Code Online (Sandbox Code Playgroud)
演示:
<script>
$(function() {
$("div").click(function() {
$("div:matches(/foobar/)").text("foobar was here")
$("div:matches(/foo\\s+bar/i)").text("some text")
$("div:matches(/^\\s+$/)").text("only spaces")
});
});
</script>
html before
<div>foobar</div>
<div>Foo Bar</div>
<div> </div>
html after
<div>foobar was here</div>
<div>some text</div>
<div>only spaces</div>
Run Code Online (Sandbox Code Playgroud)