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
});
那麼他會如何檢查ID ..? –
@RajaprabhuAravindasamy最有可能的是它必須用在像if'... like'這樣的條件語句中if(this.id =='myid'){}' –