我有以下结构:
正如您所看到的,第一个LI元素在其中包含UL,但下一个不包含UL.有没有办法通过jquery找出某个LI是否有UL内部?我想做这样的事情:
if(li has children ul) { do something }
编辑
我尝试了以下但是对所有情况都显示"是".这是我的代码和HTML.在下面的HTML中,只有"Link2"包含子UL而不包含Link1和Link3.我只想在用户点击包含子UL的LI时进行一些操作.
码
$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function() { if($('li:has(> ul)')) alert("yes"); else alert("no"); });
HTML
jfriend00.. 23
在您的特定代码中,您似乎需要使用它this
来引用单击的元素,然后从那里找到父元素,这样您只对
其中的单击进行操作:
$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function() { if($(this).closest("li").children("ul").length) { // the clicked on
在jQuery中,您可以使用.find("ul")
或.children("ul")
依赖于您是仅查找直接后代还是任何后代.
例如,如果要查明您已引用的特定标记是否具有
直接子项,则可以执行以下操作:
if ($(el).children("ul").length) { // el has a ul as an immediate descendant }
或者,如果ul可以是任何后代,那么您可以使用:
if ($(el).find("ul").length) { // el has a ul as a descendant at any level }
如果您只想找到下面的所有标签
,那么您有以下两个选项:
你可以得到一个包含所有标签的列表,
如下所示:
var tags = $("li").filter(function() { return $(this).find("ul").length !== 0; });
如果您只想要直接后代,可以使用:
var tags = $("li").filter(function() { return $(this).children("ul").length !== 0; });
然后,您可以通过在jQuery对象上调用方法来操作这些特定标记,而无需使用
if
:
var tags = $("li > ul").addClass("hasSubMenu");
Sachin.. 7
这就是你要找的
$('li:has(> ul)');
Js Fiddle演示
在您的特定代码中,您似乎需要使用它this
来引用单击的元素,然后<li>
从那里找到父元素,这样您只对<li>
其中的单击进行操作:
$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function() { if($(this).closest("li").children("ul").length) { // the clicked on <li> has a <ul> as a direct child } });
在jQuery中,您可以使用.find("ul")
或.children("ul")
依赖于您是仅查找直接后代还是任何后代.
例如,如果要查明<li>
您已引用的特定标记是否具有<ul>
直接子项,则可以执行以下操作:
if ($(el).children("ul").length) { // el has a ul as an immediate descendant }
或者,如果ul可以是任何后代,那么您可以使用:
if ($(el).find("ul").length) { // el has a ul as a descendant at any level }
如果您只想找到下面的所有<li>
标签<ul>
,那么您有以下两个选项:
你可以得到一个包含所有<li>
标签的列表,<ul>
如下所示:
var tags = $("li").filter(function() { return $(this).find("ul").length !== 0; });
如果您只想要直接后代,可以使用:
var tags = $("li").filter(function() { return $(this).children("ul").length !== 0; });
然后,您可以<li>
通过在jQuery对象上调用方法来操作这些特定标记,而无需使用if
:
var tags = $("li > ul").addClass("hasSubMenu");
这就是你要找的
$('li:has(> ul)');
Js Fiddle演示