[英]Simple jQuery if else statement
我有一個迷你腳本,這個腳本在特定的 class 中找到鏈接。 我基本上需要一個簡單的 if-else 語句。 如果a存在,則運行腳本,如果不存在,則什么也不做。
有人可以幫我嗎?
jQuery(document).ready(function() { jQuery("body").on("click", ".click-child", function() { var href = jQuery(this).find("a").attr('href'); window.location = href; }); });
根據您的問題,這就是我想您所要求的。 如果您可以將 HTML 放在某個地方,那么您在尋找什么會更清楚。
jQuery 有一個.find()
方法,它在父選擇器中搜索子選擇器,如果找到子選擇器,您可以將其用作普通 jQuery 選擇器。 否則,它什么也做不了。
如果這不是您要查找的內容,請添加更多詳細信息,我會看看是否可以為您提供更多幫助。
<section class="cards">
<div class="card">
<img />
<h3>Opens link</h3>
<a href="https://google.com">Link</a>
</div>
<div class="card">
<img />
<h3>Nothing should happen</h3>
</div>
</section>
<script>
jQuery(window).ready( function() {
jQuery('.card').click(function() {
const link = jQuery(this).find('a').attr("href")
if (link) {
window.location = link;
}
});
});
</script>
你不需要 if/else。 您可以對列表(可能包含一個元素或為空)執行.each()
) :
jQuery(function() {
jQuery("body").on("click", ".click-child", function () {
jQuery(this).find("a").first().each(function () {
window.location = this.href;
});
});
});
您可以使用:has()
選擇器僅將事件處理程序掛鈎到包含a
的.card
元素。 那么你根本不需要if
語句。 嘗試這個:
jQuery($ => {
$("body").on("click", ".click-child:has(a)", function() {
var href = $(this).find("a").attr('href');
window.location = href;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.