在jQuery中匹配精确的字符串

Matching the exact string in jQuery

本文关键字:字符串 jQuery      更新时间:2023-09-26

我有两段话:

<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,它有下划线

为什么我的代码不工作,虽然选择器是相同的?如果有正确的文本,我如何显示警告?

http://codepen.io/anon/pen/mEvOWA?编辑= 1010

这是因为JQuery对象将为条件转换为布尔值。如果不匹配,它将是length:0的JQuery对象,但仍然转换为true。只有当它是0, -0, null, false, NaN, undefined时才会被转换为false

试试这个:

if ( $("p:contains('Right text')").length ) {
  alert("Matching!");
}

$("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" );
    }
});

尝试使用for-each,然后获得每个标签p的字符串文本,并使用indexOf找到你想要匹配的字符串的位置,如果找到字符串的位置是all's> -1,否则它将是-1,如果它不是一个匹配

$('p').each(function(){
    if( $(this).text().indexOf('code example') > -1){
        console.log($(this).text());
    }
});