我有测试 div 是否有一些非空白文本内容的 javascript 代码。
这可行,但它无法区分 div 中的文本内容或样式标签声明,并且当没有文本内容但带有 css 数据的样式标签时测试失败。
问题是如何在忽略样式标签的情况下测试空文本内容?
HTML:
<div id='test1'>
<div> </div>
</div>
<div id='test2'>
<div> </div>
<style>
.style1{
border:1px;
}
</style>
</div>
Javascript:
// Works
if($('#test1').text().trim().length==0){
alert('test1 has no content!');
}
// Does not work due to style1 declaration within style tag within div
if($('#test2').text().trim().length==0){
alert('test2 has no content!');
}
最佳答案
一个选项是克隆元素并删除 style
标签:
$.fn.isTextless = function() {
var txt = this.first()
.clone()
.find('style')
.remove()
.end()
.text();
return $.trim(txt).length === 0;
}
if ( $('#test2').isTextless() ) {
alert('test2 has no content!');
}
关于javascript - jQuery 获取元素中的文本但忽略样式标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21077204/