打印每个字符串,如果它包含jQuery中的特定字符?

时间:2015-11-18 07:19:20

标签: javascript jquery html

我想获取包含特定单词的所有字符串, 例如:

<div>
    <div>
        <span>
            <h3>In Paris (Mark Bartels) worked for about 50 years.</h3>
        </span>
    </div>

    <div>
        <span>
            <h3>In America (Henry Bartels) worked for about 50 years.</h3>
        </span>
    </div>

    <div>
        <span>
            <h3>In Europe (Mark Bartels) worked for about 50 years.</h3>
        </span>
    </div>
</div>

在上面的字符串中,我必须检查“Mark”,现在我想显示包含“Mark”一词的所有字符串。

我已经尝试过以下方式,但它对我没有帮助。

var elem = $('body').find(':contains(Mark)').not('script, style, link');
var a = elem.parent();
var tag = a;
console.log(tag);
$("#sentence").append(elem.text());
$("#sentence").append('<br />');

2 个答案:

答案 0 :(得分:6)

迭代包含字符串的所有元素并附加innerText。

  1. :not(:has(*)):选择所有没有子元素的元素(不包括文本节点)Reference
  2. :contains(Mark)'):选择包含文本Mark
  3. 的所有元素
  4. :not(script):排除<script>元素
  5. // Get all the h3 elements which contains `Mark` in the innerText
    // Iterate over them
    $('body').find(':not(:has(*)):contains(Mark):not(script)').each(function() {
      // Append to the element
      console.log($(this)[0]);
      $('#sentence').append($(this).text() + '<br />');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
      <div>
        <span>
          <h3>In Paris (Mark Bartels) worked for about 50 years.</h3>
        </span>
      </div>
      <div>
        <span>
          <h3>In America (Henry Bartels) worked for about 50 years.</h3>
        </span>
      </div>
      <div>
        <span>
          <h3>In Europe (Mark Bartels) worked for about 50 years.</h3>
        </span>
      </div>
    </div>
    
    <div id="sentence"></div>

答案 1 :(得分:0)

让我们假设h3有一个共同的班级text,然后我们可以使用indexof轻松找出Mark出现的地方

$('.text').each(function () {
    if ($(this).text().indexOf('Mark') >= 0) {
        $("#sentence").append($(this).text() + '<br />');
    }
});