[英]jQuery How to make links in a div work when the entire div is clickable
I am using this code to make entire div clickable. 我正在使用此代码使整个div可单击。
$(document).on('click', '.clickable', function (e) {
window.location = $(this).find('a.main').attr("href");
return false;
});
There are around 4 link in the div and i want them to work as it should, So if the div is clicked the link with class .main
gets called/clicked., I want to make it so when other links are clicked within the div .. they work as a link should. div中有大约4个链接,我希望它们能够正常工作,所以如果单击div, .main
调用/单击类.main
的链接。我想在div中单击其他链接时这样做..他们应该作为一个链接工作。
Use e.stopPropagation();
使用e.stopPropagation();
to prevent click for background clickables when you click on some DIV
单击某些DIV
时阻止单击后台可点击
$(document).on('click', 'div.clickable', function (e) {
window.location.href = $(e.target).find('a.main').attr("href");
e.stopPropagation();
return false;
});
Simply don't return false, if the link itself was clicked: 如果单击链接本身,则不要返回false:
$(document).on('click', '.clickable', function (e) {
// only execute if no Link was clicked
if (!$(e.currentTarget).is('a')) {
window.location = $(this).find('a.main').attr("href");
return false;
}
});
This will execute your script only if the the DIV was clicked, not if the link was clicked. 这将仅在单击DIV时执行您的脚本,而不是在单击链接时执行。 So the links inside your div will behave as usual. 因此div中的链接将像往常一样运行。
$(document).on('click', '.clickable', function (e) {
window.location = $(this).find('a.main').attr("href");
return false;
});
$(document).on('click', '.clickable a', function (e) {
e.stopPropagation();
});
Do not propagate events from the anchors. 不要传播来自锚点的事件。
http://jsfiddle.net/HerrSerker/3qen2/ http://jsfiddle.net/HerrSerker/3qen2/
$(document).on('click', '.clickable a', function (e) {
e.stopPropagation();
});
$(document).on('click', '.clickable', function (e) {
self.location = $(this).find('a.main').attr("href");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.