模拟输入上的点击事件 - JavaScript

seb*_*seb 4 html javascript

我正在尝试模拟对输入标签的点击,通过点击anchor标签,这样我可以隐藏输入并将图像包裹在锚标签内。

这可以使用 jQuery 触发器函数工作,但我无法仅使用“普通”Javascript:

jQuery 版本:

let fake = $('.fake')
fake.click(function(e) {
  e.preventDefault();
  $('#user_avatar').trigger('click');
})
Run Code Online (Sandbox Code Playgroud)
#user_avatar { display: none; }
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
  <img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
Run Code Online (Sandbox Code Playgroud)

使用new Event和的 JavaScript 版本dispatchEvent

let fake = document.querySelector('.fake');
fake.addEventListener('click', function(e) {
  e.preventDefault();
  console.log('testing');
  let clickEvent = new Event('click');
document.getElementById('user_avatar').dispatchEvent(clickEvent)
})
Run Code Online (Sandbox Code Playgroud)
#user_avatar { display: none; }
Run Code Online (Sandbox Code Playgroud)
<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
  <img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
Run Code Online (Sandbox Code Playgroud)

已呈现 console.log,但未分派事件,我做错了什么?

小智 7

用:

document.getElementById('user_avatar').click();
Run Code Online (Sandbox Code Playgroud)

经测试,它有效。

  • 不适用于移动浏览器(safari ios13、chrome android 5) (3认同)

brk*_*brk 5

document.getElementById('user_avatar').click()将工作

let fake = document.querySelector('.fake');
fake.addEventListener('click', function(e) {
  e.preventDefault();
  document.getElementById('user_avatar').click()
})
Run Code Online (Sandbox Code Playgroud)
#user_avatar {
  display: none;
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
  <img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
Run Code Online (Sandbox Code Playgroud)