javascript - jQuery 改变和点击事件

标签 javascript jquery events

将事件绑定(bind)到一个元素应该是这样的:

$( document ).on( 'change', '#mySelect', showEvent );
$( document ).on( 'click', '#mySelect', showEvent );

function showEvent() {
  console.log( event.target );
}

但是通过如下所示的简单测试,将 changeclick 事件绑定(bind)到对象 mySelect 它们会在不同的元素上触发(只能通过单击文档上的任意位置更改选择和单击来更改)。

var mySelect = $( '#mySelect' );

$( document ).on( 'change', mySelect, showEvent );
$( document ).on( 'click', mySelect, showEvent );

function showEvent( event ) {
  console.log( event.target );
}

两个问题:

  1. change 事件如何运作?通过 documentation它不应该工作,因为选择器必须是一个字符串:

A selector string to filter the descendants of the selected elements that trigger the event.

  1. 应该行不通,但是,如果更改有效,为什么点击

最佳答案

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.

取自http://api.jquery.com/on/

您将选择器用作 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/

相关文章:

javascript - Ramdajs keyBy 相当于lodash

javascript - Apple.com/iphone 幻灯片 : How does it work?

javascript - 如果选择选项是 ""想要使用 javascript 三元组,则需要显示空

javascript - 在 for 循环中从 javascript 选择值

javascript - d3js - 创建类似 Asterplot 的图表(包括示例)

javascript - 我正在尝试编写一段 Javascript 代码来检查文本输入表单是否为空

jquery - 如何将 jquery Lightbox Me 默认登录按钮值更改为关闭

c# - 有委托(delegate)处理程序的事件和没有委托(delegate)处理程序的事件有什么区别?

javascript - Jquery/Javascript 应用单击 * 但不单击特定元素及其子元素

c# - 为嵌套(子)对象订阅 INotifyPropertyChanged