2016-07-29 99 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