简体   繁体   English

jQuery:在选择器中为元素赋予单个属性

[英]jQuery: Giving elements in selector individual attributes

I want to replace all svg images on my page with other svg images with the same name, but in a different directory. 我想用相同名称但在不同目录中的其他svg图像替换页面上的所有svg图像。 Specifically, the current images are in the img directory, I want to replace the source of the images to img/icon-black. 具体来说,当前图像位于img目录中,我想将图像源替换为img / icon-black。 I get all the svg elements with the following selector: 我使用以下选择器获取所有svg元素:

$.svgSelector = $(document).find('img[src$=".svg"]');

I calculate the new sources with the following: 我使用以下方法计算新来源:

var newSources = $.svgSelector.map(function(){return $(this).attr("src");}).get();

for(var i = 0; i < newSources.length; i++) {
    newSources[i] = newSources[i].replace(/^.*[\\\/]/, '');
    newSources[i] = "img/icon-black/" + newSources[i];
}

The problem arises when I want to assign the new sources to the individual elements in the selector. 当我想将新的源分配给选择器中的各个元素时,就会出现问题。

I want to do something like this: 我想做这样的事情:

for(var j = 0; j < newSources.length; j++) {
    $.svgSelector[i].attr("src", newSources[i]);
}

ie assign the source of each individual element's in the selector to its corresponding new source. 即,将选择器中每个单独元素的来源分配给其相应的新来源。

This way does not work, however. 但是,这种方式不起作用。 .attr() only returns the first src in the selector, and you cannot use it on individual elements of the selector like this either. .attr()仅返回选择器中的第一个src,您也不能像这样在选择器的各个元素上使用它。 I have also tried the .each() function but I cannot figure it out. 我也尝试过.each()函数,但我无法弄清楚。 How do I solve this? 我该如何解决?

Instead of having to map all the src attributes to a new array, and then iterating through the array to replace the values, and then rewriting the sources in yet another loop, you can all do it in a single iterative block: 不必将所有src属性映射到一个新的数组,然后遍历该数组以替换值,然后在另一个循环中重写源,而不必在单个迭代块中完成所有操作:

$.svgSelector = $(document).find('img[src$=".svg"]');

$.svgSelector.each(function() {
    newImageSrc = "img/icon-black/" + $(this).attr('src').replace(/^.*[\\\/]/, ''); 
    $(this).attr('src', newImageSrc);
});

Even better: the .attr() function actually takes a callback . 更好的是: .attr()函数实际上需要一个回调 In that sense, you can even condense it further: 从这个意义上讲,您甚至可以进一步压缩它:

$(document).find('img[src$=".svg"]').attr('src', function(i, src) {
    return "img/icon-black/" + src.replace(/^.*[\\\/]/, ''); 
});

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

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