2011-11-10 31 views
4

我有以下的HTML件:jQuery的獲得自定義(由)屬性值

<div onClick="javascript:getComments(this);" store-id="143568" class="CountryRow" style="padding: 4px;"><div class="flag flag_az"></div> &nbsp; Azerbaijan</div> 

,我想創建一個jQuery函數來獲取的store-id值。我有以下但它不工作:

getComments = function(input) { 
    fValue = $(input).val($(input).attr("store-id")); 
    alert('the ID :'+fValue); 
} 

有人可以告訴我什麼是我做錯了。

+0

對於什麼是值得的,HTML5提供了一個像這樣的自定義屬性的標準設施。 http://ejohn.org/blog/html-5-data-attributes/ – mwilson

回答

7

這完美的作品:

getComments = function(input) { 
    fValue = $(input).attr("store-id"); 
    alert('the ID :'+fValue); 
} 

http://jsfiddle.net/mHBuE/

+1

打敗了我34秒:) –

+0

非常感謝..我會接受你的答案在5分鐘(在stackoverflow後允許我)。 @LeviMorrison無論如何感謝;) –

4

在jQuery的custom selectors看看。就個人而言,我將使用HTML5 data attributes來處理這種在jQuery中已經是supported的情況。

不管它的價值,考慮到我相信什麼是你想最初執行應該像

getComments = function(input) { 
    fValue =  $(input).html($(input).attr("store-id")); 
    alert('the ID :'+fValue.html()); 

    } 
3

所有你需要做的要做的參數是:

fValue = $(input).attr("store-id"); 

您的代碼段嘗試添加到一個div(它不存在)的'value'屬性