代码之家  ›  专栏  ›  技术社区  ›  MeltingDog

JQuery:如何组合.contains()和.replaceWith()?

  •  1
  • MeltingDog  · 技术社区  · 13 年前

    我想使用JQuery将和元素的html替换为我自己的。我想我可以使用:

    $('#nav a:contains(replace me)').replaceWith('<h2>Label</h2>');
    

    但这并不奏效。我尝试过很多不同的方法,但都无济于事。

    有人知道我做错了什么吗?

    编辑: 添加了当前的html:

    <div id="nav">
    <a href="#">replace me</a>
    <a href="#">this is ok</a>
    <a href="#">this is ok</a>
    <a href="#">this is ok</a>
    </div>
    

    我想要它的样子:

    <div id="nav">
    <a href="#"><h2>Label</h2></a>
    <a href="#">this is ok</a>
    <a href="#">this is ok</a>
    <a href="#">this is ok</a>
    </div>
    
    3 回复  |  直到 13 年前
        1
  •  4
  •   adeneo    13 年前

    我想我应该这样做:

    $('#nav a').html(function(i, html) {
        return $.trim(html) == 'replace me' ? '<h2>Label</h2>' : html;
    });
    

    FIDDLE

    因为我不太喜欢 :contains

    $('#nav a:contains(replace me)').html('<h2>Label</h2>');
    

    FIDDLE

    replaceWith() 将取代整个锚点,而不仅仅是它的内容。

        2
  •  1
  •   user1697238 user1697238    13 年前

    也许对你有帮助

       $("div").find('a').each(function(index)
        {
            if(index==0){
             $(this).html("<h2>Label</h2>");
            }
    
        }); 
    
        3
  •  0
  •   hagensoft    13 年前
    $("a").text(function () {
        return $(this).text().replace("replace me", "<h2>Label</h2>"); 
    });
    

    这是一个jsfiddle链接 http://jsfiddle.net/xpfRV/1/