我使用此脚本在父元素中查找a href
,然后在单击父div时转到该链接。
jQuery(".card").click(function() {
window.location = jQuery(this).find("a").attr("href");
return false;
});
然而,我发现,如果根本没有a href
,它仍然在添加到"未定义"的链接(导致404(。
我很确定我需要一个if
来检测是否有a href
,但无法使其工作:
jQuery(".card").click(function() {
if (jQuery(this).find("a").attr("href").length {
window.location = jQuery(this).find("a").attr("href");
return false;
}
});
您需要通过长度检查a
是否存在。
jQuery(".card a",function(){
$(this).parent().addClass("has-link");
})
jQuery(".card.has-link").click(function() {
window.location = jQuery(this).find("a").attr("href");
return false;
});