【问题标题】:Get text from anchor tag从锚标记获取文本
【发布时间】:2011-04-21 17:41:11
【问题描述】:

我有以下锚标记

<a href="http://www.google.com/">Google</a>

我知道如何从锚点获取 href:

alert($(this).attr("href"));

但是如何从锚标记中获取文本,即如何获取“Google”?

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    为此使用.text()

    alert($(this).text());
    

    如果您想要标记(.text() 删除标签等),请使用 .html()

    alert($(this).html());
    

    这个 的情况下没有区别,如果你有这个:

    <a href="http://www.google.com/">Google <span>(External)</span></a>
    

    然后会有:

    $(this).text() //"Google (External)"
    $(this).html() //"Google <span>(External)</span>"
    

    【讨论】:

    • 我怎样才能只获得谷歌?
    • 任何答案都只能得到即时文本?
    【解决方案2】:

    如前所述,在使用 .text() 时,我将所有锚标记的文本组合到我的代码中:

    HTML:

    <div class="col-sm-2 jumbotron jumbotronUserRaces list-group list-group-
    userRaces" id="listGroupUserRaces">
                    <a href="" class="list-group-item active">First item</a>
                    <a href="" class="list-group-item">Second item</a>
                    <a href="" class="list-group-item">Third item</a>
                </div> 
    

    JS:

    $("#listGroupUserRaces").click(function () {
       alert($(this).text());
    });
    

    输出:

    • 第一项
    • 第二项
    • 第三项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2018-12-29
      • 1970-01-01
      • 2011-10-08
      • 2021-03-22
      • 1970-01-01
      • 2013-09-20
      相关资源
      最近更新 更多