我有这个代码:(jquery)
alert($('#feedback').text());
if ($('#feedback').text() == "") {
alert("has content");
} else {
alert("no content");
}
我用它来测试任何计划文本内容的#feedback div。然而,无论我如何格式化条件,无论我是否有内容,else 语句总是会触发。
我哪里出错了?
html:
<div id="feedback" class="hide feedback">
<p>generated message</p>
</div>
最佳答案
根据 HTML 示例,我假设当 div 应该为空时,您会遇到类似的情况:
<div id="feedback" class="hide feedback">
<p></p>
</div>
在这种情况下 .text()
div 的值不是 ""
,是"\n\n"
(两个换行符)。您需要使用 $.trim()
删除换行符。 (如果有换行符,即使没有 <p>
标签也是如此。)
if( $.trim( $( '#feedback' ).text() ) == "" ) {
alert( "no content" );
} else {
alert( "has content" );
}
关于jquery .text 作为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11614909/