Javascript 使div可单击,仅当div中存在锚点时(多个div)

Javascript 使div可单击,仅当div中存在锚点时(多个div),javascript,jquery,html,css,function,Javascript,Jquery,Html,Css,Function,给定一个基本结构,如何将一系列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

给定一个基本结构,如何将一系列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>
我遇到的问题是,click函数应用于所有div,而不仅仅是那些具有链接的div

所需的行为是仅在找到锚元素时创建完全可单击的div

在本用例中,div(
.box
)是动态生成的,不可能将元素包装在锚定标记(
)中


Fiddle:

因为您在所有的
.box.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;
    });

  }

});

但是是的,它甚至会产生问题,所以我会说给你的链接一个类,然后调用它的父…:)

普洛蒂萨特比我快了一两分钟P

if($('.boxes p a').length){
    $(".boxes .box").has('a').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)是动态生成的

将点击事件从
主体
委托给目标div,并在元素上点击
检查是否有锚定标记。要添加指针图标,请创建一个单独的函数,该函数仅当图标具有作为子项的锚定标记时,才会将图标添加到div中

$(文档).ready(函数(){
//单独函数,仅在存在指针时添加指针
addClassToElem();
$(“body”)。在('单击','框',函数()上{
if($(this.find('a').length){
window.open($(this.find(“a”).attr(“href”));
返回false;
}
})
});
函数addClassToElem(){
$('框a')。每个(函数(a,b){
$(this.parent().addClass('linkIcon'))
})
}
.linkIcon{
光标:指针;
}

一些带有

一些没有链接的文本

一些带有

一些没有链接的文本


这真是一项艰巨的工作,为什么不给“a”标记添加css,使其看起来完全像一个div,而不使用js,您将解决您的问题(也许三个哈哈;)
anchorbox
是一个集合/阵列列表,我认为它不会有
parent
Method谢谢!我最初探索了.has(),但我将其与.length()一起设置,这导致了我最初的错误。我通常会向锚点添加一个类,甚至将卡片包装在锚点中,但在这个特定实例中,卡片是使用用户生成的内容动态生成的。JS解决方案是最简单的选择,它需要尽可能少的最终用户输入。
$(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;
}