繁体   English   中英

通过jquery .on()函数将单击元素的属性值传递给外部函数

[英]Passing an attribute's value of the clicked element to an external function through jquery .on() function

作为JS和jquery的新来者,我似乎无法让这件事工作! 警报给出了undefined

this.$el.on('click', '.chorse-item',{id:$(this).attr('id')}, this.handleItem);
this.handleItem = function(event) {
        alert(event.data.id);
}

它完美地显示了“id”

this.$el.on('click', '.chorse-item', function(){alert($(this).attr('id'))});

我怀疑$(this).attr('id')是否超出了范围或什么? 原因

this.$el.on('click', '.chorse-item',{id:"Testing"}, this.handleItem);

显示“测试中”。

您的非工作版本中的$(this)位于注册onclick处理程序的函数的上下文中。 'id'是未定义的,因为它不是您当时所在的对象的属性,并且您正在将该未定义的属性分配给数据对象的id属性。

第二个工作版本中的$(this)位于调用声明函数的元素的上下文中。

谁是'id'attr你想要访问? 如果它是被点击的对象(我怀疑),那么你的第二种方法是你想要实现它的方式,并且第一种方法对你的目的是错误的。

不需要在.on方法内部传递任何数据,因为在调用函数内部已经可以使用它们:

this.$el.on('click', '.chorse-item', this.handleItem );
this.handleItem = function(event) {
    // `this` here !=  with the this `this.handleItem`
    // this here would refer to this `.chorse-item` already
    // so just calling it using `this.id` or `$( this ).attr( 'id' )`
    // in order to get clicked element's id or anything else related
    alert(this.id);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM