JQuery:将属性值附加到每个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1731138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:03:24  来源:igfitidea点击:

JQuery: Appending Attribute Value to Each Element

jquery

提问by ritsuke

Hey guys - I'm trying to append an additional url chunk to an existing attribute and simply update it.

嘿伙计们 - 我正在尝试将额外的 url 块附加到现有属性并简单地更新它。

$("img").each(function (i) {
    var originalSrc = $("img").attr('src');
    $("img").attr('src', 'http://www.domain-name.com/' + originalSrc);    
});

$("a").each(function (i) {
    var originalHref = $("a").attr('href');
    $("a").attr('href', 'http://www.domain-name.com/' + originalHref);    
});

It is counting all elements and appending a long string to the final attribute. I understand what's going on, but I'm not sure the correct way to go about this. This is obviously wrong.

它正在计算所有元素并将一个长字符串附加到最终属性。我明白发生了什么,但我不确定解决这个问题的正确方法。这显然是错误的。

Essentially, I'm scrubbing a remote page and I need to reset all relative connections to absolute.

本质上,我正在清理一个远程页面,我需要将所有相对连接重置为绝对连接。

Thanks! :-)

谢谢!:-)

回答by spoulson

Try:

尝试:

$("img").each(function () {
    var originalSrc = $(this).attr('src');
    $(this).attr('src', 'http://www.domain-name.com/' + originalSrc);    
});

回答by dave_427

Even less work with (compare http://api.jquery.com/attr/) :

甚至更少的工作(比较http://api.jquery.com/attr/):

$("img").attr('src', function(i, val){
   return 'http://www.domain.com/' + val;
});

$("a").attr('href', function(i, val){
   return 'http://www.domain.com/' + val;
});

Greets

问候

回答by CMS

Since you are using the eachmethod to loop over your elements, you should use the thiskeyword inside the callback function, to refer to the currently iterated element:

由于您正在使用该 each方法来循环您的元素,您应该this在回调函数中使用关键字来引用当前迭代的元素:

$("img").each(function (i) {
    var image = $(this), // 'this' is the image element being iterated
        originalSrc = image.attr('src');

    image.attr('src', 'http://www.domain-name.com/' + originalSrc);    
});

回答by JasonWyatt

Using your code structure:

使用您的代码结构:

$("img").each(function (i) {
    var $img = $(this);
    var originalSrc = $img.attr('src');   // use "this" in the $() function to get the current element...
    $img.attr('src', 'http://www.domain-name.com/' + originalSrc);    
});

$("a").each(function (i) {
    var $a = $(this);
    var originalHref = $a.attr('href');
    $a.attr('href', 'http://www.domain-name.com/' + originalHref);    
});

Make sure to use $(this)inside of jQuery's callback functions to retrieve the 'current' node in the node list.

确保$(this)在 jQuery 的回调函数内部使用来检索节点列表中的“当前”节点。

回答by Brandon Henry

Inside each function use $(this)instead of $(a)and $(img).

在每个函数中使用和$(this)代替。$(a)$(img)