将事件绑定(bind)到一个元素应该是这样的:
$( document ).on( 'change', '#mySelect', showEvent );
$( document ).on( 'click', '#mySelect', showEvent );
function showEvent() {
console.log( event.target );
}
但是通过如下所示的简单测试,将 change 和 click 事件绑定(bind)到对象 mySelect 它们会在不同的元素上触发(只能通过单击文档上的任意位置更改选择和单击来更改)。
var mySelect = $( '#mySelect' );
$( document ).on( 'change', mySelect, showEvent );
$( document ).on( 'click', mySelect, showEvent );
function showEvent( event ) {
console.log( event.target );
}
两个问题:
- change 事件如何运作?通过 documentation它不应该工作,因为选择器必须是一个字符串:
A selector string to filter the descendants of the selected elements that trigger the event.
- 应该行不通,但是,如果更改有效,为什么点击?
最佳答案
selector
Type: String
A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
您将选择器用作 jQuery 对象,此方法主要用于 event delegation 用于将事件绑定(bind)到动态生成的元素。所以你可以将事件直接绑定(bind)到 jQuery 对象作为
var mySelect = $( '#mySelect' );
mySelect.on( 'change', mySelect, showEvent )
.on( 'click', mySelect, showEvent );
function showEvent() {
console.log( event.target );
}
如果它是动态生成的,则移除 $
包装,只需将其作为字符串提供即可
var mySelect = '#mySelect';
$( document ).on( 'change', mySelect, showEvent );
$( document ).on( 'click', mySelect, showEvent );
function showEvent() {
console.log( event.target );
}
关于javascript - jQuery 改变和点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32508794/