【发布时间】:2015-09-06 16:02:49
【问题描述】:
您好,我正在学习 jQuery。我正在练习书中有关 attr()、removeAttr()、each() 函数的一些示例。我决定尝试不同的任务,其中一项是更改链接列表的 href 属性(例如列表中的 4 或 5),但我需要每个链接的值不同。
这是我的链接:
<h1>My Favorite Shopping List!</h1>
<a href="https://www.google.com" target="_blank">Google!</a>
<a href="https://www.yahoo.com" target="_blank">Yahoo!</a>
<a href="https://www.ebay.com" target="_blank">Ebay!</a>
<a href="https://www.amazon.com" target="_blank">Amazon</a>
然后我可以使用 each() 和 attr() 函数来遍历链接并将属性 href 更改为值 www.facebook.com。
$(document).ready(function() {
$('a').each(function() {
$(this).attr( 'href', 'http://www.facebook.com');
});
});
最终结果是:
<a href="https://www.facebook.com" target="_blank">Google!</a>
<a href="https://www.facebook.com" target="_blank">Yahoo!</a>
<a href="https://www.facebook.com" target="_blank">Ebay!</a>
<a href="https://www.facebook.com" target="_blank">Amazon</a>
但是,如果我想要这样的 ech 链接的不同值,可能的解决方案是什么:
<a href="https://www.facebook.com" target="_blank">Google!</a>
<a href="https://www.instagram.com" target="_blank">Yahoo!</a>
<a href="https://www.pinterest.com" target="_blank">Ebay!</a>
<a href="https://www.twitter.com" target="_blank">Amazon</a>
考虑减少编码!
【问题讨论】:
标签: javascript jquery