优化使用delegate()的以下代码段的最佳方法是什么?
jQuery('.menu').delegate('li.gallery', 'hover', function () { jQuery(this).children('.submenu').toggleClass('hide show'); });
jQuery('.menu').delegate('li.interior', 'hover', function () { jQuery(this).children('.submenu').toggleClass('hide show'); });
jQuery('.menu').delegate('li.exterior', 'hover', function () { jQuery(this).children('.submenu').toggleClass('hide show'); });
<li class="gallery">
<span>gallery</span>
<ul class="submenu hide">
<li class="interior">
<a href="/gallery/interior">Interior</a>
<ul class="submenu hide">
<li><a href="/gallery/interior?gallery=master-bedroom">Master Bedroom</a></li>
<li><a href="/gallery/interior?gallery=living-room">Living Room</a></li>
<li><a href="/gallery/interior?gallery=dining-room">Dining Room</a></li>
<li><a href="/gallery/interior?gallery=kitchen">Kitchen</a></li>
<li><a href="/gallery/interior?gallery=bathroom">Bathroom</a></li>
<li><a href="/gallery/interior?gallery=foyer">Foyer</a></li>
<li><a href="/gallery/interior?gallery=study">Study</a></li>
<li><a href="/gallery/interior?gallery=sunroom">Sunroom</a></li>
<li><a href="/gallery/interior?gallery=guest-room">Guest Room</a></li>
</ul>
</li>
<li class="exterior">
<a href="/gallery/exterior">Exterior</a>
<ul class="submenu hide">
<li><a href="/gallery/exterior?gallery=landscapes">Landscape</a></li>
<li><a href="/gallery/exterior?gallery=gardens">Gardens</a></li>
<li><a href="/gallery/exterior?gallery=cottages">Cottages</a></li>
<li><a href="/gallery/exterior?gallery=entry-driveway">Entry/Driveway</a></li>
</ul>
</li>
</ul>
</li>
答案 0 :(得分:2)
您可以在multiple selector (,
)选择器参数中使用.delegate()
。
但是,由于what I would consider a bug in how .delegate()
works(关闭mouseover
/ mouseout
,在进入孩子时会触发)我暂时将其清除并直接绑定,如下所示:< / p>
jQuery('.menu').find('li.gallery, li.interior, li.exterior').hover(function () {
jQuery(this).children('.submenu').toggleClass('hide show');
});