我需要通过其选择器查看页面上是否存在对象。
这通常会这样做:
startpageentry = $('#' + startpageid)
但这不会返回任何东西。我需要一个布尔值,我可以将它放入这样的 if 语句中:
if (startpageentry != 'false') {}
我怎样才能做到这一点?
使用length:
var startpageentry = $('#' + startpageid).length;
Run Code Online (Sandbox Code Playgroud)
要存储布尔结果,请使用:
var isPresent = $('#' + startpageid).length > 0;
Run Code Online (Sandbox Code Playgroud)
isPresent如果不存在,false则现在为真。
或者干脆:
if ($('#' + startpageid).length){
// exists
}
else {
// does not exist
}
Run Code Online (Sandbox Code Playgroud)