我正在尝试通过点击 anchor
标签来模拟对输入标签的点击,这样我就可以隐藏输入并将图像包装在 anchor 标签内。
这可以使用 jQuery 触发器函数,但我无法仅使用“普通”Javascript 使其工作:
jQuery 版本:
let fake = $('.fake')
fake.click(function(e) {
e.preventDefault();
$('#user_avatar').trigger('click');
})
#user_avatar { display: none; }
<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>
使用 new Event
和 dispatchEvent
的 JavaScript 版本:
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)
})
#user_avatar { display: none; }
<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>
console.log 已呈现,但事件未被分派(dispatch),我做错了什么?
最佳答案
使用:
document.getElementById('user_avatar').click();
测试成功。
关于javascript - 模拟输入点击事件 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46816088/