如何找到家长's的子级,使用querySelector而不是jQuery

How to find parent's child with querySelector instead of jQuery?

本文关键字:使用 querySelector jQuery 何找      更新时间:2023-09-26

要求我不能使用jQuery,我正在尝试解决以下问题。

布局具有相同的多个输入,如

<div class="item">
   <input type="text" />
   <input type="file" />
</div>
<div class="item">
   <input type="text" />
   <input type="file" />
</div>​​​​​​​​​​​​​​​​​​​​​

当单击文本框时,javascript需要查找同级文件输入。

$('input[type=text]').click(function() {
    $(this).parent(".item")
        .find('input[type=file]')
        .trigger('click');
});

注意:我不能使用Id,因为页面上有多个(多个)"项目"。

您可以使用vanila脚本事件处理程序和元素(如)之间的下一个同级关系

//get all the text input elements which are descendants of .item
var els = document.querySelectorAll('.item input[type="text"]');
for (var i = 0; i < els.length; i++) {
  //add click handler
  els[i].addEventListener('click', function() {
    //nextElementSibling is supported from IE9
    this.nextElementSibling.click()
    //or
    //this.parentNode.querySelector('input[type="file"]').click()
  })
}
<div class="item">
  <input type="text" />
  <input type="file" />
</div>
<div class="item">
  <input type="text" />
  <input type="file" />
</div>

  • nextElement同级