Javascript 为jquery中的元素组更改一个属性名,但更改不同的值

Javascript 为jquery中的元素组更改一个属性名,但更改不同的值,javascript,jquery,Javascript,Jquery,嗨,我正在学习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=

嗨,我正在学习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>
最终结果是:

<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 link的值不同,可能的解决方案是什么:

<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>


考虑更少的编码

您也可以使用
.prop
而不是
.attr


假设您有一个包含不同url的数组,然后使用
每个
回调函数中的索引依次应用每个url:

var urls = [
  'https://www.facebook.com',
  'https://www.instagram.com',
  'https://www.pinterest.com',
  'https://www.twitter.com'
];
$(document).ready(function(index) {
  $('a').each(function() {
      $(this).attr('href', urls[index]);
   });
});
$(document).ready(function() {
var linksArray = ["https://www.facebook.com", "https://www.instagram.com"] //all links
 $('a').each(function(i,v) {
      $(this).prop( 'href', linksArray[i]);
   });
});
var urls = [
  'https://www.facebook.com',
  'https://www.instagram.com',
  'https://www.pinterest.com',
  'https://www.twitter.com'
];
$(document).ready(function(index) {
  $('a').each(function() {
      $(this).attr('href', urls[index]);
   });
});