gpt4 book ai didi

javascript - jQuery:如果元素为空,不包括空格和注释

转载 作者:行者123 更新时间:2023-11-29 17:01:10 24 4
gpt4 key购买 nike

以下代码检查元素中是否没有内容(不包括空格或换行符)。除了忽略空格外,我还希望它尽可能忽略注释或任何非 HTML 标记的内容。我怎样才能做到这一点?

        if( $.trim( $("#element").html() ) == '' ) {
// do something if empty
}

最佳答案

根据您的评论:

I want to check if the element contains any nodes, but not comments and whitespace.

要确定元素是否包含不包括注释的节点,请使用 .children() .

要确定元素是否包含不包括空格的文本内容,请使用 $.trim().text() .

结合这些,您的代码变为:

if($('#element').children().length>0 && $.trim($("#element").text())!=='')

因为非零数字是 truthy和空字符串是 falsy ,这可以缩短为:

if($('#element').children().length && !$.trim($("#element").text()))

在下面的示例中,element2 是唯一符合条件的元素(只有空格的非注释节点):

function test(el) {
if($(el).children().length && !$.trim($(el).text())) {
return 'Success - children with no visible text';
}
else {
return 'Failure - '+
$(el).children().length+' children -'+
$(el).text();
}
}

$('body').append('<p>element1: '+test('#element1')+'</p>');

$('body').append('<p>element2: '+test('#element2')+'</p>');

$('body').append('<p>element3: '+test('#element3')+'</p>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element1">
Lorem ipsum
<span>dolor</span>
<!-- nothing to see here -->
<strong>sit <em>amet</em></strong>
</div>

<div id="element2">
<span> </span>
<!-- nothing to see here -->
<strong> <em> </em></strong>
</div>

<div id="element3">
<!-- nothing to see here -->
</div>
<hr>

看看如何.children()可能会提供信息不同于 .contents() ,它确实包括注释节点和文本节点:

constants='|element|attribute|text|cdata section|entity reference|entity|processing instruction|comment|document|document type|document fragment|notation'.split('|');

$('#info').children().each(function() {
var t= $(this)[0];
$('#children').append(
'<tr><td>'+(t.tagName || '')+
'<td>'+constants[t.nodeType]+
'<td>'+(t.textContent.trim() || '<em>whitespace</em>')
);
})

$('#info').contents().each(function() {
var t= $(this)[0];
$('#contents').append(
'<tr><td>'+(t.tagName || '')+
'<td>'+constants[t.nodeType]+
'<td>'+(t.textContent.trim() || '<em>whitespace</em>')
);
})
body, table {
font: 12px verdana;
}

table {
border: 1px solid #666;
border-collapse: collapse;
}

td, th {
border-right: 1px solid #ddd;
border-bottom: 1px solid #bbb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="info">
Lorem ipsum
<span>dolor</span>
<!-- nothing to see here -->
<strong>sit <em>amet</em></strong>
</div>
<hr>
<strong>.children():</strong>
<table id="children">
<tr><th>Tag<th>Node type<th>Text content
</table>
<hr>
<strong>.contents():</strong>
<table id="contents">
<tr><th>Tag<th>Node type<th>Text content
</table>

关于javascript - jQuery:如果元素为空,不包括空格和注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27993878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com