开发者

isset in jQuery? [duplicate]

This question already has answers h开发者_如何学JAVAere: Closed 11 years ago.

Possible Duplicate:

Finding whether the element exists in whole html page

i would like make somethings:

HTML:

<span id="one">one</span>
<span id="two">two</span>
<span id="three">three</span>

JavaScript:

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

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

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

if (!isset($("#four"))){
   alert('no');
}

LIVE:

http://jsfiddle.net/8KYxe/

how can I make that?


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

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

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

if (($("#four")).length == 0){
   alert('no');
}

This is what you need :)


You can use length:

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


function isset(element) {
    return element.length > 0;
}

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


Or, as a jQuery extension:

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

// later ...
if ( $("#id").exists() ) {
  // do something
}


php.js ( http://www.phpjs.org/ ) has a isset() function: http://phpjs.org/functions/isset:454


You can simply use this:

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

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

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

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.


function el(id) {
  return document.getElementById(id);
}

if (el('one') || el('two') || el('three')) { 
  alert('yes');

} else if (el('four')) {
  alert('no');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜