
JavaScript 是基于多范式的动态脚本语言,可以用作动态网页设置。在动态网页开发的过程中,如果某个元素不存在,很容易会报错,所以在使用前,我们最好先判断一下JavaScript中元素是否存在。本文介绍JavaScript中判断元素是否存在的两种方法:1、使用递归的方法判断;2、使用jQuery 对象的 length 属性可以帮助判断。
1、使用递归的方法判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # include <cstdio>
# include <iostream>
# include <queue>
using namespace std;
int k,x;
bool f(int y){
if (y > x) return false;
if (y == x) return true;
if (f( 2 * y + 1 ) || f( 3 * y + 1)) return true;
return false;
}
int main(){
cin >> k;
cin.get();
cin >> x;
int a = k;
bool b = f(a);
if (b){
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
|
2、使用jQuery 对象的 length 属性可以帮助判断。
1 2 3 4 5 6 7 8 9 | var lzcBlog = $( '#lzcBlog' );
if (lzcBlog.length > 0)
{
console.log( 'ID 为 lzcBlog 的元素存在于页面上。' );
}
else
{
console.log( 'ID 为 lzcBlog 的元素不存在。' );
}
|
以上就是JavaScript中判断元素是否存在的两种方法,大家可以直接套用代码进行检测哦~更多js学习教程:js教程。