jquery查找并替换元素中的关键字

时间:2016-01-22 03:26:25

标签: javascript jquery

有没有办法循环查找并替换元素中的某些单词?这是我尝试但不打球的原因。

html示例:

<div class="homepage-boxes">
    <h2 class="ty-mainbox-simple-title">Shop Interior Bean Bags</h2>
    <h2 class="ty-mainbox-simple-title">Shop Outdoor Bean Bags</h2>
    <h2 class="ty-mainbox-simple-title">Buy Kids Bean Bags</h2>
    <h2 class="ty-mainbox-simple-title">Buy Baby Bean Bags</h2>
</div>

JS:

$('.homepage-boxes .ty-mainbox-simple-title').each(function() {
    $(this).html().replace('Shop','');
    $(this).html().replace('Buy','');
    $(this).html().replace('Bean Bags','');
});

预期产出:

<div class="homepage-boxes">
    <h2 class="ty-mainbox-simple-title">Interior</h2>
    <h2 class="ty-mainbox-simple-title">Outdoor</h2>
    <h2 class="ty-mainbox-simple-title">Kids</h2>
    <h2 class="ty-mainbox-simple-title">Baby</h2>
</div>

4 个答案:

答案 0 :(得分:1)

DOM

之后你必须reset html

&#13;
&#13;
replace
&#13;
$('.homepage-boxes .ty-mainbox-simple-title').each(function() {
    $(this).html($(this).html().replace('Shop','').replace('Buy','').replace('Bean Bags',''));
 
});
&#13;
&#13;
&#13;

答案 1 :(得分:1)

问题是,即使你要替换内容,html也不会被设置回元素。

您可以将.html()的setter版本与正则表达式替换为

&#13;
&#13;
$('.homepage-boxes .ty-mainbox-simple-title').html(function(i, html) {
  return html.replace(/Shop|Buy|Bean Bags/g, '');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="homepage-boxes">
  <h2 class="ty-mainbox-simple-title">Shop Interior Bean Bags</h2>
  <h2 class="ty-mainbox-simple-title">Shop Outdoor Bean Bags</h2>
  <h2 class="ty-mainbox-simple-title">Buy Kids Bean Bags</h2>
  <h2 class="ty-mainbox-simple-title">Buy Baby Bean Bags</h2>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您必须将替换的字符串放入h2以显示结果

$('.homepage-boxes').find('h2.ty-mainbox-simple-title').each(function() {
  $(this).html($(this).html().replace('Shop', ''));
  $(this).html($(this).html().replace('Buy', ''));
  $(this).html($(this).html().replace('Bean Bags', ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="homepage-boxes">
  <h2 class="ty-mainbox-simple-title">Shop Interior Bean Bags</h2>
  <h2 class="ty-mainbox-simple-title">Shop Outdoor Bean Bags</h2>
  <h2 class="ty-mainbox-simple-title">Buy Kids Bean Bags</h2>
  <h2 class="ty-mainbox-simple-title">Buy Baby Bean Bags</h2>
</div>

答案 3 :(得分:0)

$('.homepage-boxes .ty-mainbox-simple-title').each(function() {
    var $this = $(this);
    $this.text( $this.text().replace('Shop','') );
    $this.text( $this.text().replace('Buy','') );
    $this.text( $this.text().replace('Bean Bags','') );
});