2010-04-25 159 views
1

我有選擇元素使用jQuery這裏屬性麻煩是我的HTML:與jQuery選擇問題

<a class="myselector" rel="I need this value"></a> 

<div class="someClass" id="someID"> 
...bunch of elements/content 
<input type="button" name="myInput" id="inputID" title="myInput Title" /> 
...bunch of elements/content 
</div> 

...一堆元素/內容

在這裏,我試圖讓相對這裏myselector的價值是我試過,但它不工作:

$('#inputID').live('click',function(){ 
console.log($(this).closest('a.myselector').attr('rel')); 
}); 

也試過這個,因爲所有被包裹在包裝DIV:

$('#inputID').live('click',function(){ 
console.log($(this).parent('div.wrapper').find('a.myselector').attr('rel')); 
}); 

我得到undefined在這兩種情況下的螢火蟲值,我使用live,因爲div#someID加載在文件中,當頁面第一次加載時它不存在。任何建議,我怎麼能得到我的選擇器rel值?

編輯:

然而,當我尋找('a.myselector')沒有rel屬性,我提醒Object object,並得到執行console.log東西[]

回答

3

這應該工作:

console.log($(this).closest('div.wrapper').find('a.myselector').attr('rel')); 

你的第一個例子在你的問題不起作用,因爲你試圖選擇的錨標記是not a parent/ancestor

console.log($(this).closest('a.myselector').attr('rel')); 

,如果你改變.parent().parents()你的第二個例子就是工作,因爲.parent()只有穿越one level了DOM,所以下面:

console.log($(this).parents('div.wrapper').find('a.myselector').attr('rel')); 
+0

@ Karim79這似乎沒什麼問題,你的第二選擇還是輸出不確定,但仍然第一個作品,謝謝某些時候我會接受這個答案時間流逝 – 2010-04-25 13:28:30

0

剛剛送走我的頭頂,你有沒有試過accesing你的rel值沒有使用live(即直接id $(「inputid」)。attr(「rel」))?

我通常在遇到像這樣的問題時一個一個消除嫌疑人。

0

請嘗試this

$('#inputID').live('click',function(){ 
    // alert($(this).parent().parent().html()); 
alert($(this).parent().parent().find('a.myselector').attr('rel')); 
}); 

HTH

+0

Tnx Raja但這是不實際的,它不是一個靜態網站 – 2010-04-25 15:19:42