如何用jQuery判断是否有特定的孩子(.haschild(’#test ‘))?

$('target').haschild('#test')应该是true

$('target').haschild('#test[att="test"]')应该是true

$('target').haschild('#no')应该是false

只有$('target')可用。

你可以测试一些方法,这里有一个:

 if($("#target > #test").length){ //true } else { //false } 

如果您使用jQuery插件,您实际上可以使用您在示例中使用的语法:

 $.fn.haschild = function(selector){ return ($("> " + selector, this).length > 0); } $(function(){ alert($('#target').haschild('#test')); // Alerts true alert($('#target').haschild('#test[att="test"]')); // Alerts true alert($('#target').haschild('#no')); // Alerts false }); 

这是一个有效的例子

 $('target').children('#test').length == 0 

要么

 $('target > #test').length == 0 

修改此处的示例以适合此示例,您可以扩展JQuery以使用新的:haschild选择器以及方法,

您可以使用$('#target:haschild(#test)').haschild('#test')

 $.fn.haschild = function(selector){ function filterMethod(){ if (selector) { return $(this).children(selector).length >= 1; } return $(this).children().length >= 1; } return this.filter(filterMethod); } $.expr[':'].haschild = function(objNode,intStackIndex,arrProperties,arrNodeStack){ var selector = arrProperties[3]; if (selector) { return $(objNode).children(selector).length >= 1; } return $(objNode).children().length >= 1; }