jQuery 从特定子项获取链接

jQuery obtain links from specific child

本文关键字:获取 链接 jQuery      更新时间:2023-09-26

可以做以下事情吗?

我有这个div:

<div class="articleBoxContent">
   <h2><a href="myLink">Title</h2>
   <p>
      <a href="anotherLink">
        <img src="img.jpg">
      </a>
   </p>
   <p>My text is so awesome! I like ponies and cookies.</p>
</div>

以及以下 jQuery 代码段:

$(".articleBoxContent").click(function() {
   window.location = $(this).find("h2").find("a").attr("href"); 
   return false;
});

我想做的是,当我单击我的div 时,只有当div 在 p 元素中不包含另一个链接时,它才会将我发送到 H2 元素 (myLink) 中包含的链接。

但是我不知道如何对jQuery说将H2元素中的链接与p元素中的链接区分开来。知道吗?

谢谢!

使用:

$(".articleBoxContent").click(function() {
    var el = $(this);
    if( el.find('p a[href]').length == 0 ){
        el.find('h2 a[href]').trigger('click');
    } // if
});

p元素内部进行检查:

$(".articleBoxContent").click(function() {
    if ($(this).find("p a").length) {
        //Found some anchor elements inside a "p" tag, do nada
        return false;
    } else
        //Didnt find an anchor inside the "p" tags - redirect
        window.location = $(this).find("h2").find("a").attr("href"); 
    }
});

试试看:

$(".articleBoxContent").click(function(e) {
 e.preventDefault();
 e.stopPropagation();
 var $this = $(this);
 if(!$this.find('p a').length) {
   window.location = $this.find("h2 a").attr("href"); 
 }
 return false;

});