我有两段:
<p>Some text</p>
<p>Another text</p>
和这个jQuery代码:
if ( $("p:contains('Right text')") ) {
alert("Matching!");
};
$( "p:contains('Right text')" ).css( "text-decoration", "underline" );
只有在文本Right text
时才会显示提醒。但是当您加载页面时,它会每次显示。脚本的第二部分应为Right text
的段落添加下划线并且它有效 - 如果它包含Right text
,则它具有下划线。
为什么我的代码不起作用,虽然选择器是相同的?如果文本正确,我该如何显示警告?
答案 0 :(得分:2)
那是因为JQuery对象将被转换为条件的布尔值。
如果它不匹配,它将是length:0
的JQuery对象,但仍会转换为true
。如果它是0, -0, null, false, NaN, undefined
,它只会转换为false。
请改为尝试:
if ( $("p:contains('Right text')").length ) {
alert("Matching!");
}
答案 1 :(得分:1)
$("p:contains('Right text')")
总是返回一个数组。此数组已定义,因此如果您尝试将其转换为布尔值,则始终获得true
。检查数组的长度 - 它应该大于0。
正确的代码:
if ( $("p:contains('Right text')").length > 0 ) {
alert("Matching!");
};
$( "p:contains('Right text')" ).css( "text-decoration", "underline" );
注意:如果Right text blah blah
它也会有下划线,因为它包含Right text
。如果要查看完整内容,请执行
$( "p" ).each(function() {
if ( $( this ).html() == "Right text" ) {
alert( "Matching" );
$( this ).css( "text-decoration", "underline" );
}
});
答案 2 :(得分:1)
尝试使用for-each,然后获取每个标记p的字符串文本,并使用indexOf查找要匹配的字符串的位置,如果找到该字符串,则位置为全部&gt; -1另外明智的是,如果它不匹配则为-1
$('p').each(function(){
if( $(this).text().indexOf('code example') > -1){
console.log($(this).text());
}
});