使用 jQuery .trigger() 触发两个 .bind() 事件
Use jQuery .trigger() to fire two .bind() events
如果我使用单个事件,例如:
$("#total").keyup(function(){
// Code here
});
我可以像这样触发它:
$("#total").trigger('keyup');
但是如果我有类似的东西:
$("#total").bind("keyup change", function(e) {
// Some logic here
});
是否可以使用 .trigger()
触发绑定事件?
根据文档:
.trigger( eventType [, extraParameters ] ): eventType is a string containing a JavaScript event type.
如果您使用的是 jQuery 的现代版本,最好使用 on 而不是 bind:
As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
所以,你需要:
$(function () {
$("#total").bind("keyup change", function(e) {
console.log('event: ' + e.type);
});
$("#total").trigger('keyup').trigger('change');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<button id="total">Click Me</button>
如果我使用单个事件,例如:
$("#total").keyup(function(){
// Code here
});
我可以像这样触发它:
$("#total").trigger('keyup');
但是如果我有类似的东西:
$("#total").bind("keyup change", function(e) {
// Some logic here
});
是否可以使用 .trigger()
触发绑定事件?
根据文档:
.trigger( eventType [, extraParameters ] ): eventType is a string containing a JavaScript event type.
如果您使用的是 jQuery 的现代版本,最好使用 on 而不是 bind:
As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
所以,你需要:
$(function () {
$("#total").bind("keyup change", function(e) {
console.log('event: ' + e.type);
});
$("#total").trigger('keyup').trigger('change');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<button id="total">Click Me</button>