Javascript jQuery 中的 isset 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7526554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:36:02  来源:igfitidea点击:

isset in jQuery?

phpjavascriptjqueryhtml

提问by Paul Attuck

Possible Duplicate:
Finding whether the element exists in whole html page

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

i would like make somethings:

我想做点什么:

HTML:

HTML:

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

JavaScript:

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/

http://jsfiddle.net/8KYxe/

how can I make that?

我怎么能做到呢?

回答by Snicksie

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 :)

这就是你需要的:)

回答by realshadow

You can use length:

您可以使用length

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

回答by Richard Dalton

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

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

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



Or, as a jQuery extension:

或者,作为 jQuery 扩展:

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

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

回答by prehfeldt

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

php.js ( http://www.phpjs.org/) 有一个isset()函数:http: //phpjs.org/functions/isset:454

回答by RobG

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

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

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

回答by Nicklasos

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.

对不起,我的错误,它不起作用。