我看过类似的帖子,并尝试了它们的解决方案中的语法,但都没有生效。
我想根据链接文本,更改页面上某一类型所有链接的href属性。以下是我现在拥有的代码:
$('.class li a').attr('href', '#' + $(this).text());
$(this).text()
似乎没有返回任何内容。因为我有一段时间没有用过jQuery,所以对这个问题感到困惑。我也尝试了 .val()
和 .html()
。
我看过类似的帖子,并尝试了它们的解决方案中的语法,但都没有生效。
我想根据链接文本,更改页面上某一类型所有链接的href属性。以下是我现在拥有的代码:
$('.class li a').attr('href', '#' + $(this).text());
$(this).text()
似乎没有返回任何内容。因为我有一段时间没有用过jQuery,所以对这个问题感到困惑。我也尝试了 .val()
和 .html()
。
$(this)
不是指当前的 a
标签。$('.class li a').each(function(){
$(this).attr('href', '#' + $(this).text());
});
$.each()
:它比循环快几倍:http://jsperf.com/jquery-each-vs-for-loops/7 - Jasperthis
引用$('.class li a').attr('href', '#' + $(this).text());
不是链接标签。jQuery提供第二个参数,也可以是一个函数,在其中this
将引用链接标签。因此,像下面这样的东西应该就可以解决问题了。
试一试,
$('.class li a').attr('href', function () {
return '#' + $(this).text()
});
$(".class li a").each(function(){
$(this).attr('href', '#' + $(this).text());
});