ita*_*312 4 javascript jquery jquery-focusout
我有一个焦点事件
$('.alpha').on("focusout", function () {...});
Run Code Online (Sandbox Code Playgroud)
我想从代码中的其他地方触发它。
我试过$('#input12').focus().blur();
,也试过$('#input12').trigger("focusout")
编辑:我正在使用动态生成的元素。
但没有运气...
该元素#input12具有类名,alpha因此我希望触发 focusout 事件。
有没有办法完成它?
这是我尝试执行https://jsfiddle.net/jnmnk68d/时的 jsfiddle 示例
您需要将事件委托给非动态父元素。
在这个例子中,我们监听 上的focusout事件,form但只有当事件的目标与选择器匹配时才触发我们的函数(在本例中".alpha")。这样,可以在现在或将来匹配的任何元素上触发事件。
$("form").on("focusout", ".alpha", function() {
console.log("focusout happened!");
});
Run Code Online (Sandbox Code Playgroud)
这是一个完整的演示,可让您了解如何使用委托事件触发动态插入内容的事件。
$("form").on("focusout", ".alpha", function() {
console.log("focusout happened!");
});
Run Code Online (Sandbox Code Playgroud)
$(function() {
$("form").on("focusout", ".alpha", function(e) {
console.warn("focusout triggered on " + e.target.outerHTML);
});
//example trigger
//click the link to trigger the event
$("a").on("click", function(e) {
e.preventDefault();
$("#input12").trigger("focusout");
});
//demo injecting content
//click the create button then focus out on the new element to see the delegated event still being fired.
var i = 12;
$("form").on("submit", function(e) {
e.preventDefault();
var id = "input" + (++i);
$(this).find("fieldset").append("<input id='" + id + "' class='alpha' placeholder='" + id + "' />");
});
});Run Code Online (Sandbox Code Playgroud)