在jQuery中?

Pau*_*uck 17 html javascript php jquery

可能重复:
查找元素是否存在于整个html页面中

我想做点事情:

HTML:

<span id="one">one</span>
<span id="two">two</span>
<span id="three">three</span>
Run Code Online (Sandbox Code Playgroud)

JavaScript:

if (isset($("#one"))){
   alert('yes');
}

if (isset($("#two"))){
   alert('yes');
}

if (isset($("#three"))){
   alert('yes');
}

if (!isset($("#four"))){
   alert('no');
}
Run Code Online (Sandbox Code Playgroud)

生活:

http://jsfiddle.net/8KYxe/

我该怎么做?

Sni*_*sie 28

if (($("#one").length > 0)){
   alert('yes');
}

if (($("#two").length > 0)){
   alert('yes');
}

if (($("#three").length > 0)){
   alert('yes');
}

if (($("#four")).length == 0){
   alert('no');
}
Run Code Online (Sandbox Code Playgroud)

这就是你需要的:)

  • 如果未找到id,则会抛出错误 (3认同)
  • `if(!! $('#one')){alert('yes'); `` - 等等.这是!! JS中的double not运算符. (2认同)

rea*_*dow 18

你可以使用length:

if($("#one").length) { // 0 == false; >0 == true
    alert('yes');
}
Run Code Online (Sandbox Code Playgroud)

  • 不需要> 0,因为0无论如何都被评估为false. (3认同)
  • @Richard:是的,但是`> 0`更具表现力,因此更容易阅读.每个人都可能不会立即明白`0`评估为'false`. (2认同)

Ric*_*ton 8

function isset(element) {
    return element.length > 0;
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/8KYxe/1/


或者,作为jQuery扩展:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)