我是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;
}
這可能幫助:http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery – 2013-04-05 16:15:54