测试元素是否存在jquery

时间:2012-07-12 09:24:27

标签: jquery

我正试着看看是否存在这些问题。我用.length测试了它,但我不确定我是否做得对。即使select-sub-domain类没有li,它也会发出警告。

http://jsfiddle.net/ST8Be/

if ($('ul.expul > li.select-sub-domain').length < 0) {
var sub_doma = "Not set";
alert("no");
} else {
alert("yes");
var sub_domain = $('li.select-sub-domain').attr('id');
var sub_domainSplit = sub_domain.split('-');
var sub_doma = sub_domainSplit[1];
}​

<ul class="one expul">
<li class='select' id=eng-88>1</li>
<li class='select' id=eng-89>2</li>
<li class='select' id=eng-90>3</li>
<li class='select' id=eng-91>4</li>
<li class='select' id=eng-92>5</li>
<li class='select' id=eng-93>6</li>
<li class='select' id=eng-94>7</li>
<li class='select' id=eng-95>8</li>
<li class='select' id=eng-96>9</li>
<li class='select' id=eng-97>10</li>
<li class='select' id=eng-98>11</li>
<li class='select' id=eng-99>12</li>                    
</ul>

<ul class="two expul hide">
 <li class='select' id=fin-100>1</li>
<li class='select' id=fin-101>2</li>
<li class='select' id=fin-102>3</li>
<li class='select' id=fin-103>4</li>
<li class='select' id=fin-104>5</li>
<li class='select' id=fin-105>6</li>
<li class='select' id=fin-106>7</li>
<li class='select' id=fin-107>8</li>                
</ul>

<ul class="three expul hide">
 <li class='select' id=three-108>1</li>
 <li class='select' id=three-109>2</li>
 <li class='select' id=three-110>3</li>
 <li class='select' id=three-111>4</li>
 <li class='select' id=three-112>5</li>
 <li class='select' id=three-113>6</li>
</ul>​

2 个答案:

答案 0 :(得分:0)

更改$('ul.expul > li.select-sub-domain').length > 0)

$('ul.expul > li.select-sub-domain').length == 0)

你是代码,如果长度大于0,警告号码。哪个不对。

当长度等于0时,它应该发出警告。

答案 1 :(得分:0)

只需更改你的If语句,现在你在没有物品时警告是,而在没有物品时则不警告。

if ($('ul.expul > li.select-sub-domain').length === 0) {
   var sub_doma = "Not set";
   alert("no");
} else {
   alert("yes");
   var sub_domain = $('li.select-sub-domain').attr('id');
   var sub_domainSplit = sub_domain.split('-');
   var sub_doma = sub_domainSplit[1];
}​

http://jsfiddle.net/PeterForss/ST8Be/2/

修改 因为0 in JavaScipt is falsy,它可以写得更短,就像这样:

if ($('ul.expul > li.select-sub-domain').length) {
   alert("yes");
   var sub_domain = $('li.select-sub-domain').attr('id');
   var sub_domainSplit = sub_domain.split('-');
   var sub_doma = sub_domainSplit[1];
} else {
   var sub_doma = "Not set";
   alert("no");
}​