[英]How to get the attr with jQuery?
<div class="item">
<p><img src="images/photos_sample1.jpg"
border="0" rel="images/google_map.jpg"></p>
<p>Dining Area</p>
</div>
<div class="item">
<p><img src="images/photos_sample2.jpg"
border="0" rel="images/sample_photo.jpg"></p>
<p>Pool Area</p>
</div>
我有上面的HTML代碼,我想在單擊圖像時獲取rel
屬性的值。 我寫了這個jQuery腳本,但它似乎不起作用:
$('div.item').click(function() {
var getvalue = $('this > p > img').attr('rel');
alert(getvalue);
});
替換這個:
var getvalue = $('this > p > img').attr('rel');
有了這個:
var getvalue = $(this).find('p > img').attr('rel');
因為它是現在你在做一個全局搜索與文字標簽名稱元素this
等效代碼也將是:
var getvalue = $('p > img', this).attr('rel');
雖然從它的外觀來看,這些項目是圖像/標題組合,你不會真正期待其他圖像,在這種情況下,最好只做:
var getvalue = $(this).find('img').attr('rel');
或者也許給它一個描述性的類並用img.someclassname
替換img
- 這將使得如果你以后編輯HTML你的Javascript不會因為你的特定選擇器而中斷。
此外,您可以將click事件綁定到圖像本身:
$('div.item img').click(function() {
var getvalue = $(this).attr('rel');
});
$('div.item').click(function() {
var getvalue = $(this).find('> p > img').attr('rel');
alert(getvalue);
});
你不能像這樣使用'this'。
嘗試:
$('div.item').click(function() {
var getvalue = $('p > img', this).attr('rel');
alert(getvalue);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.