簡體   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