【问题标题】:Change href based on text in a tag根据标签中的文本更改 href
【发布时间】:2014-08-04 23:34:19
【问题描述】:

我有一堆<a> 标签,其中包含不同的字符串。我希望能够根据每个单独标签内的文本设置这些标签的 url。

例如,我有

<a class="list-group-item">example</a>
<a class="list-group-item">example2</a>
<a class="list-group-item">example3</a>

并且我希望能够使第一个的 url 等于 /example/,第二个等于 /example2/,第三个等于 /example3/

这个 jQuery 函数使所有的href="/example/"

$(function(){
    customURL = $( ".list-group-item" ).html();
    $("a").attr("href", customURL)
});

【问题讨论】:

  • 使用循环遍历元素并花时间阅读一些 jQuery 初学者教程。
  • 为什么你不能直接生成你的a标签并正确设置href属性?如果你真的不能,也许知道.attr can accept a function as second parameter 可以帮助你。

标签: javascript jquery html href


【解决方案1】:
$('a.list-group-item').attr('href', function(){
    return '/' + $(this).text() + '/';
})

jsFiddle example

【讨论】:

    【解决方案2】:

    使用这个 jQuery:

    $('.list-group-item').each(function(){
       var $this=$(this);
       var customURL=$this.html();
       $this.attr('href',customURL);
    });
    

    【讨论】:

    • 只需添加到文档api.jquery.com/html 的链接,其中说 .html() 函数返回匹配元素集中第一个元素的内容。因此,由于有 3 个匹配的元素, .html() 只返回第一个的内容,即:“example”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 2019-01-30
    相关资源
    最近更新 更多