简体   繁体   English

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

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

As a new comer to JS and jquery, I just can't seems to get this thing working! 作为JS和jquery的新来者,我似乎无法让这件事工作! The alert gives undefined ! 警报给出了undefined

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

It shows the "id" perfectly with 它完美地显示了“id”

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

I suspect the $(this).attr('id') is falling out of scope or something? 我怀疑$(this).attr('id')是否超出了范围或什么? cause 原因

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

Shows the "Testing". 显示“测试中”。

$(this) in your non-working version is in the context of the function registering the onclick handler. 您的非工作版本中的$(this)位于注册onclick处理程序的函数的上下文中。 'id' is undefined because it's not an attribute of the object you are in at the time, and you are assigning that undefined attribute to the id property of the data object. 'id'是未定义的,因为它不是您当时所在的对象的属性,并且您正在将该未定义的属性分配给数据对象的id属性。

$(this) in the second working version is in the context of the element calling the declared function. 第二个工作版本中的$(this)位于调用声明函数的元素的上下文中。

Who's 'id' attr are you wanting to get access to? 谁是'id'attr你想要访问? If it's the object that's clicked (which I suspect) then your second method is the way you want to be implementing this, and the first method is wrong for your purpose. 如果它是被点击的对象(我怀疑),那么你的第二种方法是你想要实现它的方式,并且第一种方法对你的目的是错误的。

No need to pass any data inside .on method, as it already available inside the calling function : 不需要在.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