gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:15:32 25 4
gpt4 key购买 nike

作为 JS 和 jquery 的新手,我似乎无法让这个东西工作!警报显示未定义!

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);

显示“测试”。

最佳答案

无需在 .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);
}

关于javascript - 通过 jquery .on() 函数将单击元素的属性值传递给外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com