2014-05-20 26 views
0

使用事件委托,是否有办法检查被触发的元素是否具有特定的属性或特定的类或ID?有没有办法在使用事件委派时检查元素的属性?

<ul> 
    <li><button>Make the first paragraph appear</button></li> 
    <li><button>Make the second paragraph appear</button></li> 
    <li><button>Make the third paragraph appear</button></li> 
</ul> 

<div> 
    <p class="first">First paragraph</p> 
    <p class="second">Second paragraph</p> 
    <p class="third">Third paragraph</p> 
</div> 

假设所有段落最初隐藏,点击第一个按钮,第一款出现,点击第二个按钮,第一段是隐藏的,则显示第二款,当第三个按钮是点击,第二段隐藏,同时保持第一段隐藏。

到目前为止,我的解决方案是为每个特定的按钮制作一个事件处理程序,并隐藏其他两个段落,但只显示一个。它可以工作,但如果元素数量增加,则每个元素所需的事件处理程序也会增加。有一个更好的方法吗?预先感谢任何回应!

+0

像http://jsfiddle.net/arunpjohny/RMYst/1/? –

+0

当然。如果不是,事件代表团将不可能。 –

回答

2

如果按钮和段落的指数相同,则可以利用.index()

$('button').click(function() { 
    var idx = $(this).index('ul li button'); 
    $('div p').eq(idx).show().siblings('p').hide();  
}); 

Fiddle Demo

,或者您可以使用data-*属性,如果该指数是不同的:

<ul> 
    <li><button data-parapgraph="first">Make the first paragraph appear</button></li> 
    <li><button data-parapgraph="second">Make the second paragraph appear</button></li> 
    <li><button data-parapgraph="third">Make the third paragraph appear</button></li> 
</ul> 

<div> 
    <p class="first">First paragraph</p> 
    <p class="second">Second paragraph</p> 
    <p class="third">Third paragraph</p> 
</div> 

然后申请.data()检索data-*属性:

$('button').click(function() { 
    var parapgraph = $(this).data('parapgraph'); 
    $('p.' + parapgraph).show().siblings('p').hide();  
}); 

Fiddle Demo

1

我认为,如果能确认按钮的位置和p要显示的都是一样的,那么你可以使用像

jQuery(function ($) { 
    var $ts = $('div > p'); 
    $('ul button').click(function (e) { 
     $ts.hide().eq($(this).parent().index()).show() 
    }) 
}) 

演示了基于索引的解决方案:Fiddle

0

我宁愿用<a>代替按钮,然后使用href属性的识别,并使用ID的段落

<ul class="link-list"> 
    <li><a href="#first">Make the first paragraph appear</a></li> 
    <li><a href="#second">Make the second paragraph appear</a></li> 
    <li><a href="#third">Make the third paragraph appear</a></li> 
</ul> 

<div> 
    <p id="first">First paragraph</p> 
    <p id="second">Second paragraph</p> 
    <p id="third">Third paragraph</p> 
</div> 

$('.link-list').on('click','li > a',function(){ 
    //id would be something like #first 
    var id = $(this).attr('href'); 
    //we use it as a selector (you can also use $('div.classname').find(id); 
    var $paragraph = $(id); 
    // we show our desired paragraph and hide its siblings 
    $paragraph.show().siblings().hide(); 
    // make sure the browser does not follow the link/anchor 
    return false; 
}); 

Fiddler

+0

对不起,这将导致页面跳跃点击,试图按照链接。 – PeterKA

+0

这就是'返回false;'是/我在那里添加了一些评论 – UnLoCo

相关问题