[英]Make div clickable, only when anchor is present in div (multiple divs)
给定一个基本结构,如何将一系列div转换为链接而不将每个 div转换为链接? 这是一个例子:
<div class="boxes">
<div class="box"><p>Some text with a <a href="https://www.google.com">link</a></p></div>
<div class="box"><p>Some text without a link</p></div>
<div class="box"><p>Some text with a <a href="https://www.example.com">link</a></p></div>
<div class="box"><p>Some text without a link</p></div>
</div>
我正在使用相关的jQuery使divs可点击:
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
我遇到的问题是click函数应用于所有 div而不仅仅是那些带有链接的div。
所需的行为是仅在找到锚元素时才创建完全可单击的div。
出于此用例的目的,div( .box
)是动态生成的,并且.box
将元素包装在锚标记( <a href="#"><div> </div></a>
)中。
小提琴: https : //jsfiddle.net/fu8xLg0d/
因为您在所有.boxes .box
类.boxes .box
类上添加事件侦听器,这些类都是您的div。
只需添加以下内容:
$(".boxes .box").has('a')...
将它缩小到只包含a
元素的那些
使用.parent
来解决你的目的:
$(document).ready(function() {
if($('.boxes p a').length){
$("a").parent().parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
但是,是的,它甚至可以创建一个问题所以我会说给你的链接一个类,然后调用它的父... :)
Plotisateur只是打了我一两分钟! :P
if($('.boxes p a').length){
$(".boxes .box").has('a').click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
无论如何这里是代码: https : //jsfiddle.net/fu8xLg0d/1/
You can try this.
$(document).ready(function() {
var anchorbox =$(".boxes p a");
if(anchorbox.length>0){
$(anchorbox).parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
这个小小的改动,可以帮助您解决问题。
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
});
}
});
与您的代码的区别是,另外添加一个检查
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
div(.box)是动态生成的。
将click事件从body
委托给目标div, click
元素检查它是否具有锚标记。 对于添加指针图标,创建一个单独的函数,只有当它具有锚标记作为子标记时才会将图标添加到div
$(document).ready(function() { // separate function to add pointer only if a is present addClassToElem(); $("body").on('click', '.box', function() { if ($(this).find('a').length) { window.open($(this).find("a").attr("href")); return false; } }) }); function addClassToElem() { $('.box a').each(function(a, b) { $(this).parent().addClass('linkIcon') }) }
.linkIcon { cursor: pointer; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="boxes"> <div class="box"> <p>Some text with a <a href="https://www.google.com">link</a></p> </div> <div class="box"> <p>Some text without a link</p> </div> <div class="box"> <p>Some text with a <a href="https://www.example.com">link</a></p> </div> <div class="box"> <p>Some text without a link</p> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.