2016-07-29 59 views
0

我有以下给出的以下DOM结构,我想在两个场景中找到超链接按钮(a)。我已经使头部(header1和recordHeader1)可点击(光标:指针)。因此,如果我在header1或recordHeader1中的(name,job_title)上单击任意位置(如果单击headerTitle),我想查找超链接按钮并执行某些点击功能。可能会有更多这样的场景,但在所有场景中,都有一个像以下给出的父头,并且父头始终具有DOM中某处的超链接元素。请让我知道我在这里做错了什么。遍历到特定的孩子 - jQuery/Javascript

方案1:

<div class="header1"> 
    <a href="#" class="downArrow k-icon k-minus"></a> <!-- This element --> 
    <img class="foundIcon" src="https://google.com"> 
    <div class="headerTitle">Contacts</div> 
</div> 

方案2:

<div class="recordNew"> 
     <div class="recordHeader1"> 
     <ul> 
      <li> 
      <div class="arrowContainer"> 
       <a href="#" class="downArrow k-icon k-minus"></a> <!-- This element --> 
      </div> 
      </li> 
      <li> 
      <div class="nameContainer"> 
       <span class="name">John Doe </span> 
      </div> 
      </li> 
     </ul> 
     </div> 
     <span class="job-title">Marketing Professional </span> 
     </div> 
    </div> 

我已经试过?

// This is a generic function that makes the header clickable based on any element click 
function makeRowClickable() { 
    $(".headerTitle, .name, .job_title, .foundIcon").on("click", function(e) { 
    // doesn't seem to work and find the correct element 
    console.log($(e.target).closest(".header1").find(".downArrow")); 
    }); 
} 
+0

你不必在你的第二个例子中,'header1'类的元素,所以'.closest(”头1" )'不会发现什么 –

+0

是的同意,这只是一个例子来解释我想要实现的。 – Neophile

+0

点击框中是否只有一个链接? –

回答

2

试试这个

const headerClick = (e, header, downArrow) => { 
    // programatically click on the anchor tag 
    downArrow.click(); 
} 

// get all .header1 elements 
[...document.querySelectorAll('.header1')] 

    // add all .recordHeader1 elements to the array 
    .concat([...document.querySelectorAll('.recordHeader1')]) 

    // add event listener on each .header1 and .recordHeader1 
    .forEach((header) => header.addEventListener('click', (e) => { 

    // inside the click handler send the event, the header element, and its child downarrow element 
    headerClick(e, header, header.querySelector('.downArrow')) 

    })); 
+0

嗨丹尼尔,这将迎合任何头元素?我的标题元素并不总是.header1。 – Neophile

+0

你只需要将选择器连接到你的数组中。 'querySelector'将会遍历你的dom树。 –

+0

嗨@Daniel_L,这个工作,但是当我点击我的其他超链接元素时,它也执行downArrow点击。有没有办法避免这种情况? – Neophile