我是 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;
}
最佳答案
简单地不要测试,如果没有匹配的元素,这不会产生任何错误:
$( ".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
}
关于jQuery:仅当元素存在时如何执行某些操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15838628/