2014-04-26 23 views
0

我有一個委託,當某些DOM元素被點擊使用他們的id或類時被調用,並且我正在函數中使用'this',但是如何找出哪個類或ID'這'實際上是?如果這個函數是一個特定的類

這裏是我的代碼:

$(document).delegate("#lg-menu li, #xs-menu li, .list-item", "click", function(e) { 
    a = $(this).attr("alpha"); 
    b = $(this).attr("bravo"); 
    c = $(this).attr("charlie"); 
    d = parseInt($(this).attr("delta")); 
} 

回答

1

this是指觸發事件,所以你可以只使用兩種DOM方法或DOM對象jQuery的方法來檢查它或它的父母:

$(document).delegate("#lg-menu li, #xs-menu li, .list-item", "click", function(e) { 
    var item = $(this); 
    // see which selector the item matches 
    if (item.is("#lg-menu li") { 
     // must be #lg-menu li 

    } else if (item.is("#xs-menu li") { 
     // must be #xs-menu li 

    } else { 
     // must be .list-item 

    } 
} 

.is()包裹了整個選擇Ë爲你估價。你也可以詢問元素的各個屬性,如:

item.hasClass(".list-item")    // does the item have a .list-item classname 
item.parents("#lg-menu").length !== 0  // does the item have a #lg-menu parent 
item.parents("#xs-menu").length !== 0  // does the item have a #xs-menu parent 
this.tagName === "LI"      // is the item an <li> tag 

不過,如果你真的需要知道它是哪一個項目,那麼你可能應該只使用單獨的事件處理程序爲每個項目並保存試圖找出每一次是哪一個的工作。

$(document).delegate("#lg-menu li", "click", function(e) { 
    // code here 
}); 

$(document).delegate("#xs-menu li", "click", function(e) { 
    // code here 
}); 

$(document).delegate(".list-item", "click", function(e) { 
    // code here 
}); 
1

得到的這個ID,你可以閱讀的DOM元素的id屬性像

var id = this.id; 

,以檢查它是否有一個特定的類,使用.hasClass()

var hasActive = $(this).hasClass('active') 
+0

那麼他會如何檢查ID ..? –

+0

@RajaprabhuAravindasamy最有可能的是它必須用在像if'... like'這樣的條件語句中if(this.id =='myid'){}' –

0

,您可以登錄您的this對象,並找出哪些字段,它包含:

$(document).delegate("#lg-menu li, #xs-menu li, .list-item", "click", function(e) { 
    console.log(this); 
    ... 
} 

您也可以設置爲一個功能手動this使用bind(thisArg)方法 described here

相關問題