2012-11-22 71 views
3

我有可能需要一些優化幾種不同的任務:JQuery的做不同的事情根據不同的選擇。對使用()方法

$('.container').on('click', '.one', function() { 
    // do task one 
}); 

$('.container').on('click', '.two', function() { 
    // do task two 
}); 

$('.container').on('click', '.three', function() { 
    // do task three 
}); 

合併到以下幾點:

$('.container').on('click', '.one, .two, .three', function() { 
    // How to selectively perform each task, based on the trigger/ selector? 
    // Think of if (event.type === 'mouseenter') // do sumthing 
}); 

的問題是如何根據每個觸發器/選擇器有選擇地執行每個不同的任務?還是有更好的方法來執行此操作?

感謝

+0

我不明白你爲什麼建議if(event.type ==='mouseenter')'如果想改變上面代碼中的任務是元素,而不是事件。你只有點擊事件。 – Diego

+0

只是一個關於選擇性觸發器的例子,謝謝 – swan

回答

6
$('.container').on('click', '.one, .two, .three', function() { 
    if ($(this).hasClass("one")) { 
    // do task one 
    } 
    if ($(this).hasClass("two")) { 
    // do task two 
    } 
    if ($(this).hasClass("three")) { 
    // do task three 
    } 
}); 
+0

$(this)是否指這裏的每個選擇器迭代?謝謝 – swan

+0

'$(this)'是指被點擊的元素。 – Diego

+0

應該是if(){} else if(){} ... –

3

您可以使用hasClass方法:

$('.container').on('click', '.one, .two, .three', function() { 
    var $this = $(this); 
    if ($this.hasClass('one')) { 
    // 
    } else if ($this.hasClass('two')) { 
    // 
    } else { 
    // 
    } 
}); 
+1

如果某個元素有多個類,這段代碼就會與原來的不同。 – Diego

8

更好的方法可能只是對鏈.on()電話:

$('.container').on('click', '.one', function() { 
    // do task one 
}).on('click', '.two', function() { 
    // do task two 
}).on('click', '.three', function() { 
    // do task three 
}); 

這樣做,將刪除需要額外的處理來檢查元素是否每個都有一個特定的類事件處理程序被觸發。

+2

更何況看起來更優雅 – Esailija

+0

雅這是更好 –

+0

喜歡它。但不好的一面是,每個事件沒有直接綁定到它的元素上有一定的代價。這樣每次點擊容器中的某個元素時,jQuery會詢問元素是「.one」還是「.two」或「.three」。唯一的區別是我們不會看到它。 – Diego

相關問題