我想通過jQuery添加屬性data-pic
多個IMG標籤:如何檢測jQuery中的當前元素?
$('#description img').attr('data-pic', $(this).attr('src'))
但是,$(this).attr('src')
將無法正常工作。我需要的是我正在使用的當前元素(img)的src。
我想通過jQuery添加屬性data-pic
多個IMG標籤:如何檢測jQuery中的當前元素?
$('#description img').attr('data-pic', $(this).attr('src'))
但是,$(this).attr('src')
將無法正常工作。我需要的是我正在使用的當前元素(img)的src。
你需要使用一個回調函數來使用上下文this
關鍵字。
$('#description img').attr('data-pic', function() {
return $(this).attr('src');
});
或甚至'return this.getAttribute(「src」)'因爲這裏真的不需要jQuery包裝器。或者,如果可以得到解析的值而不是相對的,'return this.src;':-) –
@ T.J.Crowder同意...':D'第二個比較容易,我很懶。我將使用'this.src'! ':D' –
我通過jQuery添加屬性數據-PIC到圖像(大於1):
您需要使用一個循環的各圖像上。
$('#description img').each(function(){
$(this).attr('data-pic', $(this).attr('src'))
})
用'each'做它*是可能的*,但效率低下;只需使用'attr'的回調函數即可。 –
要做到這一點,你可以使用直接循環使用each()
。這會給你的處理函數中的this
參考:
$('#description img').each(function() {
$(this).attr('data-pic', $(this).attr('src'));
});
或者你可以提供一個功能attr()
將每個元素實例工作:
$('#description img').attr('data-pic', function() {
return $(this).attr('src');
});
使用'的console.log(本);',看看什麼東西顯示在console./ –
@PraveenKumar:更重要的是,使用調試器,看看發生了什麼事情。當你可以通過內置在瀏覽器中的調試器打開燈光時,用'console.log'手電筒在黑暗中徘徊是沒有意義的。 –
無法在項目列表上使用$(this).attr()。 –