如何使用 querySelector 而不是 jQuery 查找 parent 的 child?

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

要求规定我不能使用 jQuery 我正在尝试解决以下问题 w/out 它。

布局有多个像这样的相同输入

<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,因为页面上有多个(许多)"items"。

您可以使用 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>