我需要将jQuery.click仅应用于第一级项目.我怎么做? 这是我的清单: ul id="adminMenu" li id="A" h3a href=""Item 1/a/h3 /li li id="B" h3Item 2/h3 ul style="display: block;" li id="a1" Sub Item 1 /li li id="a2" Sub Item
这是我的清单:
<ul id="adminMenu"> <li id="A"> <h3><a href="">Item 1</a></h3> </li> <li id="B"> <h3>Item 2</h3> <ul style="display: block;"> <li id="a1"> Sub Item 1 </li> <li id="a2"> Sub Item 2 </li> <li id="a3"> Sub Item 3 </li> </ul> </li> <li id="C"> <h3>Item 3</h3> <ul style="display: none;"> <li> Sub Item 4 </li> <li> Sub Item 5 </li> </ul> </li> </ul>
这是jQuery
jQuery('#adminMenu > li').click(function(){ alert('test'); });
UPDATE
单击子菜单项时,仅当我单击列表项A,B或C时,警报不应触发.
解决方案1
这是基于Marcels建议的工作代码.
jQuery('#adminMenu > li > h3').click(function(e) { var activeUL = jQuery("#adminMenu > li ul:visible"); var activeLI = jQuery("#adminMenu > li ul:visible").parent('li:first'); var clicked = jQuery(this).parent('li:first'); // Close submenu activeUL.hide('fast'); // Open submenu if( activeLI.attr('id') != clicked.attr('id') ) clicked.children('ul').show('fast'); });
解决方案2
这是基于Eyelids建议的工作代码.
jQuery('#adminMenu > li').click(function(e) { var clicked = jQuery(e.target); // Ensure we're checking which list item is clicked, // other children should be allowed if(!clicked.is('li') && clicked.parents('li').length > 0) { // :first ensures we do not select higher level list items clicked = clicked.parents('li:first'); } // If clicked list item is a child of another list item, we'll exit here if(!clicked.is('#adminMenu > li')) { return; } var activeUL = jQuery("#adminMenu > li ul:visible"); var activeLI = jQuery("#adminMenu > li ul:visible").parent('li:first'); // Close submenu activeUL.hide('fast'); // Open submenu if( activeLI.attr('id') != clicked.attr('id') ) clicked.children('ul').show('fast'); });
多谢你们!如果没有你的帮助,我绝不会做到这一点!