简体   繁体   English

更改一个属性名称,但jQuery中的元素组的值不同

[英]changing one attr name but different values for group of elements in jquery

Hi I am in process of learning jQuery. 嗨,我正在学习jQuery。 I was practicing some examples from the book reading about attr(), removeAttr(), each() functions. 我正在阅读本书中的一些示例,这些示例涉及attr(),removeAttr()和each()函数。 I decided to try different tasks and one of them was to change href attribute for a list of links( like 4 or 5 in the list), but I needed the value to be different for each link. 我决定尝试不同的任务,其中之一是更改链接列表的href属性(例如列表中的4或5),但是我需要每个链接的值都不同。

Here are my links: 这是我的链接:

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

Then I can use each() and attr() functions to loop through the links and change the attribute href to value www.facebook.com for example. 然后,我可以使用each()和attr()函数循环链接,并将属性href更改为值www.facebook.com。

$(document).ready(function() {
 $('a').each(function() {
      $(this).attr( 'href', 'http://www.facebook.com');
   });
});

the final result is: 最终结果是:

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

But what is the possible solution if I want different values for ech link like this: 但是,如果我想要这样的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>

Considering less coding! 考虑减少编码!

You can also use .prop instead of .attr . 您也可以使用.prop而不是.attr Difference between .prop & .attr .prop.attr之间的.prop

$(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]);
   });
});

Say you have an array with your different urls, then use index in each callback function to apply successively each url: 假设您有一个具有不同URL的数组,然后在each回调函数中使用index依次应用每个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]);
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM