[英]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.