jQuery:只有元素存在时如何做某事?

时间:2013-04-05 16:10:50

标签: jquery

我是jQuery的新手,我认为这个问题已被多次回答。但我无法建议如何找到它。在编写jQuery代码时,我经常编写重复选择器的结构:

if( $( ".someclass .someclass #someid" ).filter( ":visible" ) )
{
  $( ".someclass .someclass #someid" ).filter( ":visible" ).click();
  // This must be executed only if element was found.
  return;
}
// This must be executed only if first element not found
if( $( ".someotherclass #someotherid" ).filter( ":hidden" ) )
{
  $( ".someotherclass #someotherid" ).filter( ":hidden" ).show();
  return;
}

如您所见,重复选择器文本。是否可以在“if()”中重复使用最后匹配的选择器的结果?例如,像:

if( $( ".someclass .someclass #someid" ).filter( ":visible" ) )
{
  $( ":last-result" ).click();
  return;
}
if( $( ".someotherclass #someotherid" ).filter( ":hidden" ) )
{
  $( ":last-result" ).show();
  return;
}

2 个答案:

答案 0 :(得分:3)

只是不测试,如果没有匹配的元素,这不会产生任何错误:

$( ".someclass .someclass #someid:visible").click();

这就是说,因为你只能有一个具有给定id的元素,你可能应该使用

$("#someid:visible").click();

现在,假设您确实想要进行测试,那么您可以使用

$("#someid:visible").each(function(){
     var $element = $(this);

     // use $element

});

另一个基本解决方案是在测试之前缓存元素:

 var $element = $("#someid");
 if ($element.is(":visible")) {
     // use $element
 }

答案 1 :(得分:1)

如果你真的只想在元素存在时做某事

$('element').length == 0; // no element found

通过使用.length属性,我们可以测试元素是否存在,或者是否在页面中找到它。

Read more