简体   繁体   中英

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();});

You can try this

 var _file = document.getElementsByClassName('file')[0]; //Return a NodeList
_file.onclick = function(){
  document.getElementsByClassName('none')[0].click();
}

jsFiddle

EDIT

If there are multiple elements with same class

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))
}

Demo2

This might be the most accurate equivalent:

document.querySelector(".file")
    .addEventListener("click", function(){
  document.querySelector(".none").click();
});

For a more cross-browser alternative for .click() : How can I trigger a JavaScript event click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM