[英]Can't get ATTR value from IMG SRC using EACH (jquery)
The 'each' function returns 3 times undefined while I am trying to get 3 different results with 3 different URLS. 当我尝试通过3个不同的URL获得3个不同的结果时,“每个”函数返回3次未定义的结果。
var src = $('img').each(function(){
$(this).attr("src");
alert(src);
});
I found a couple of answer on SO but none of them seems to answer this (really basic) problem. 我在SO上找到了几个答案,但是似乎都没有一个答案可以回答这个(非常基本的)问题。
What I want to do is replace every img url with a more specific URL 我要做的是将每个img网址替换为更具体的网址
ex: 例如:
a.jpg --> a-ok.jpg
b.jpg --> b-ok.jpg
c.jpg --> c-ok.jpg
That's why I need the URL of all the img using an EACH. 这就是为什么我需要使用EACH来获取所有img的URL的原因。
Please help. 请帮忙。
Thanks 谢谢
Your code is wrong. 您的代码是错误的。 By assigning
src
variable to $('img').each
you will get elements collection, not src
attributes. 通过将
src
变量分配给$('img').each
您将获得元素集合,而不是src
属性。
Should be: 应该:
$('img').each(function(){
var src = $(this).attr("src");
alert( src );
});
To replace src
attributes you will need do this inside each
callback function. 要替换
src
属性,您需要在each
回调函数中执行此操作。
For example like this: 例如这样:
$('img').each(function(){
var src = $(this).attr("src");
$(this).attr("src", src.replace('.', '-ok.'));
});
$('img').each(function(){
var src = $(this).attr("src");
console.log( src );
// now override the src
var pos = src.lastIndexOf("."); // there can be numerous . in the url
$(this).attr('src', ( src.substring(0,pos) + '-OK.'+src.substring(pos+1) ) ) ;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.