2013-01-12 127 views
0

好的,我點擊一次就可以發現多件事情,但我想知道是否有更好的方法來格式化或做到這一點?有沒有更好的方法來格式化多個事件?

<ul><li>Hello</li><li>Welcome</li><li>Howdy</li></ul> 
<div class="first">Goodbye</div><div class="second">See ya</div><div class="third">Later Gator</div> 

$('li:first-child').click(function(){ 
$('li:nth-child(2)').removeClass('this'); 
$('li:nth-child(3)').removeClass('this'); 
$('.second').hide(); 
$('.third').hide(); 
$('li:first-child').addClass('this'); 
$('.first').show(); }); 

分別這樣做,我需要點擊其他對象時的相同過程。

jsfiddle

回答

0

這個怎麼樣?

$('li:first-child').click(function(){ 
    $(this).addClass('this').next().removeClass('this').next().removeClass('this'); 
    $('.second, .third').hide(); 
    $('.first').show(); 
}); 
1

您可以使用關鍵字this它指的是點擊的元素。當然你的頁面中還有其他的div或li元素,你可以添加類來區分這些元素和其他元素。

$('li').click(function(){ 
    var $this = $(this), ind = $this.index(); 
    $this.addClass('this').siblings().removeClass('this'); 
    $('div').hide().eq(ind).show() 
}); 
0
$('ul').on('li','click', function(ev) { 
    // your code 
}); 

由於這種方法避免了多個事件綁定。 jQuery只是在UL元素上尋找一個單擊事件,使得dom起泡,但如果我錯了,請糾正我。

相關問題