[英]What's the equivalent of this code in pure/native javascript?
<label class="file">File</label>
<input class="none" type="file">
jQuery的:
$('.file').click(function(){ $('.none').click();});
你可以试试这个
var _file = document.getElementsByClassName('file')[0]; //Return a NodeList
_file.onclick = function(){
document.getElementsByClassName('none')[0].click();
}
编辑
如果有多个元素具有相同的类
var _file = document.getElementsByClassName('file'); //Return a NodeList
var _none = document.getElementsByClassName('none');
for(var x = 0;x<_file.length;x++){
(function(x){ //Creating closure
_file[x].addEventListener('click',function(){
console.log(x)
document.getElementsByClassName('none')[x].click();
})
}(x))
}
这可能是最准确的等价物:
document.querySelector(".file")
.addEventListener("click", function(){
document.querySelector(".none").click();
});
对于.click()
的更多跨浏览器替代方案: 如何触发JavaScript事件单击
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.