[英]jQuery change and click events
Binding events to an element should be something like: 将事件绑定到元素应该是这样的:
$( document ).on( 'change', '#mySelect', showEvent );
$( document ).on( 'click', '#mySelect', showEvent );
function showEvent() {
console.log( event.target );
}
But by doing a simple test as shown below, binding the change and click events to the object mySelect they are triggered on different elements ( change only by changing the select and the click by clicking anywhere on the document ). 但是,通过执行如下所示的简单测试,将更改和单击事件绑定到对象mySelect,它们将在不同元素上触发( 仅通过单击文档上的任意位置更改选择和单击来更改 )。
var mySelect = $( '#mySelect' );
$( document ).on( 'change', mySelect, showEvent );
$( document ).on( 'click', mySelect, showEvent );
function showEvent( event ) {
console.log( event.target );
}
Two questions: 两个问题:
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.Type: String
一个选择器字符串,用于过滤触发事件的所选元素的后代。 If the selector is null or omitted, the event is always triggered when it reaches the selected element.如果选择器为null或省略,则事件始终在到达所选元素时触发。
Taken from http://api.jquery.com/on/ 摘自http://api.jquery.com/on/
You are using the selector as a jQuery object, this method is mainly using for event delegation for binding event to dynamically generated element. 您正在使用选择器作为jQuery对象,此方法主要用于将事件委托绑定到动态生成的元素。 So you can bind event directly to the jQuery object as
因此,您可以将事件直接绑定到jQuery对象
var mySelect = $( '#mySelect' );
mySelect.on( 'change', mySelect, showEvent )
.on( 'click', mySelect, showEvent );
function showEvent() {
console.log( event.target );
}
If it's dynamically generated then remove the $
wrapping just provide it as string 如果它是动态生成的,那么删除
$
wrap只需将其作为字符串提供
var mySelect = '#mySelect';
$( document ).on( 'change', mySelect, showEvent );
$( document ).on( 'click', mySelect, showEvent );
function showEvent() {
console.log( event.target );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.