jQuery:如何根据内容选择段落

时间:2013-02-02 19:51:56

标签: jquery

  

可能重复:
  jQuery select based on text

我正在学习drupal。我想在网站上添加一些jquery。我知道我可以,也可能稍后,回去添加ID和课程,以便我可以更方便地访问,但我想知道如何使用' has'或者'内容'和/或'过滤'正确。

在我的页面上,我有很多段落,我想根据内容选择<p>,然后对它们执行某些操作,例如我想要:

jQuery('p').has('What is Supplemental').css('background-color', 'red')

我该怎么做?

此处的网站示例:http://surety.lfwebz.com

感谢您的见解。

4 个答案:

答案 0 :(得分:1)

如何:包含?

$('p:contains("What is Supplemental")').css('background-color','red');

答案 1 :(得分:1)

$('p').filter(function(){
    return $(this).text().indexOf("What is Supplemental") > -1;
}).css('background-color', 'red');

答案 2 :(得分:1)

您可以尝试这样的事情:

$('p').filter(function () {
    return $(this).text() == 'What is Suppemental';
}).css('background-color', 'red');

由于:contains可能会导致问题,因为它不会检查完全匹配,例如,p:contains("What is Supplemental")...也会匹配“什么是补充[填充空白]”或“[填充” THE BLANK]什么是补充“。

编辑:

使用indexOf时也是如此,但它只适用于附加到匹配项的文字。

答案 3 :(得分:0)

each

jQuery('p').each(function(i){
 str = jQuery(this).html();
 if(str.indexOf('What is Supplemental') !== -1){
   jQuery(this).css('background-color', 'red');
 }
});