2016-03-08 14 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(匿名函數的返回)