<div id="target">
<div id="test" att="test"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
$('target').haschild('#test') 应该 true
$('target').haschild('#test[att="test"]') 应该 true
$('target').haschild('#no') 应该 false
只有$('target')可用.
$('target').children('#test').length == 0
Run Code Online (Sandbox Code Playgroud)
要么
$('target > #test').length == 0
Run Code Online (Sandbox Code Playgroud)
你可以测试一些方法,这里有一个:
if($("#target > #test").length){
//true
} else {
//false
}
Run Code Online (Sandbox Code Playgroud)
如果您使用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
});
Run Code Online (Sandbox Code Playgroud)