如何使用querySelector而不是jQuery查找父级的孩子?
问题描述:
要求决定我不能使用jQuery,我试图解决以下问题。如何使用querySelector而不是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');
});
注意:由于页面上有多个(很多)“项目”,因此我无法使用Ids。
答
元素之间的下一个兄弟关系
您可以使用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>