找不到与“触发器”相关的非jQuery等价物 [英] cannot find non-jQuery equivalent for "trigger"
本文介绍了找不到与“触发器”相关的非jQuery等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Tigran Saluev建议以下答案手动触发选择文件的提示,但代码使用jQuery。他的代码如下:
Tigran Saluev suggested the following answer to manually triggering a prompt to select a file, but the code used jQuery. His code was a follows:
var input = $(document.createElement("input"));
input.attr("type", "file");
input.trigger("click");
在我的项目中,我想要相同的效果,但没有jQuery。我以为我在这里有:
In my project, I wanted the equivalent effect but without jQuery. I thought I had it here:
var input = document.createElement("input");
input.setAttribute("type", "file");
input.dispatchEvent(new Event("click"));
但没有任何反应。我做错了什么?
But nothing happens. What am I doing incorrectly?
推荐答案
在你的情况下,只需要一个简单的click()调用来触发事件。或者,如果您想使用调度事件,则需要创建鼠标事件并触发它。
In your case a simple click() call is all that is needed to trigger the event. Or if you want to use dispatch event, you want to create a Mouse Event and trigger that.
var fi = document.querySelector("#f");
// simple call to click()
document.querySelector("button.test1").addEventListener("click", function() {
f.click()
});
// Or with dispatch event
document.querySelector("button.test2").addEventListener("click", function() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
fi.dispatchEvent(event);
});
<input id="f" type="file" />
<button class="test1" type="button"> CLICK ME 1</button>
<button class="test2" type="button"> CLICK ME 2</button>
这篇关于找不到与“触发器”相关的非jQuery等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文