遍历特定的孩子 - jQuery / Javascript

时间:2016-07-29 14:41:36

标签: javascript jquery html jquery-traversing

我有下面给出的DOM结构,我想在两个场景中找到超链接按钮(a)。我已经使标题(header1和recordHeader1)可点击(光标:指针)。因此,如果我点击在header1中的任何地方说(如果我点击headerTitle)或者记录在RecordHeader1中的(name,job_title),我想找到超链接按钮并执行某些点击功能。可能会有更多这样的场景,但在所有场景中,都有一个父头像下面给出的那个,父头总是在DOM中的某处有超链接元素。请让我知道我在这里做错了什么。

情景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")); 
  });
}

1 个答案:

答案 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'))

  }));