2016-03-08 62 views
-1

我有一个片段,我试图与之合作;我有几个产品,我抓住了源代码,将它拆分为“?”并将其放入数组中,然后用新链接替换“img.item-img”src。

但是,我没有使用循环或$('this')来区分它们的唯一性。所以如果我有三个项目,他们都获得第一个src代码。

<script> 
$(document).ready(function() { 
    $("img.item-img").each(function() { 
    str = $("img.item-img").attr('src'); 


    arr = str.split("?"); 
    var new_link = arr[0]; 

    $("img.item-img").attr('src', new_link); 
    }); 
</script> 

enter image description here

+1

你的问题是? – BenM

+1

你的问题是什么?因为你说过你不用'$(this)',但为什么不呢? (这是我的问题......) –

回答

0

里面的每一个回调函数,你需要使用$(这)是指当前正在遍历的元素。

<script> 
$(document).ready(function() { 
    $("img.item-img").each(function() { 
    str = $(this).attr('src'); 


    arr = str.split("?"); 
    var new_link = arr[0]; 

    $(this).attr('src', new_link); 
    }); 
</script> 
+0

非常感谢! 我只是不明白如何正确地做到这一点。我还是新鲜的。但这是完美的 –

0

正如你正确识别,您需要使用this关键字作为$()功能单一的参数:

$('img.item-img').each(function() { 
    var str  = $(this).attr('src'), 
     arr  = str.split("?"); 

    $(this).attr('src', arr[0]); 
}); 

或者,你可以使用attr()功能中的匿名函数调用:

$('img.item-img').attr('src', function() { 
    var arr = $(this).attr('src').split('?'); 
    return arr[0]; 
}); 

jsFiddle Demo(匿名函数的返回)