如何用data-href的值替换href?

时间:2011-06-20 15:49:37

标签: jquery

我有html如下

<a href="" data-href="/somefile.php?id=10&refcode=/test.php">Hello</a>

我需要用data-href中的值替换href,以便上面的内容变成类似

的内容
<a href="/somefile.php?id=10&refcode=/test.php">Hello</a>

//the following doesnt work .. 

$(function() {
 $('a[data-href]').attr('href', $(this).attr('data-href'));
});

有什么建议吗?基本上我想从搜索引擎/机器人等出于某种原因隐藏一些链接所以我很高兴如果我可以得到上述工作或者如果你能提出任何更好的想法来达到同样的目的?谢谢。

1 个答案:

答案 0 :(得分:9)

在这种情况下,

$(this)不会引用a元素。

尝试

$('a[data-href]').each(function() { 
 $(this).attr('href', $(this).attr('data-href'));
});

使用each(function() {})会将this关键字绑定到函数内的a元素。

相关问题