[英]Click event on dynamic elements not working
在framework7
,如何在動態元素上添加click
事件?
如果我先在視圖上添加元素,則click事件的工作原理如下:
<div class="test">Click Me</div>
$$('.test').on('click', function () {
myApp.alert("Gotcha!");
});
但是,如果我有動態元素,尤其是動態添加到virtual-list
元素,則無法使click
事件起作用。 什么是正確的方法?
我什至嘗試了內聯函數,例如: <div class="test" onclick="myFunction();">Click Me</div>
,但這仍然行不通。
您可以使用:
// Live/delegated event handler
$$(document).on('click', 'a', function (e) {
console.log('link clicked');
});
對於您的情況:
$$(document).on('click', '.test', function(e){
console.log('Some code...');
});
這是docs 。 滾動到events
部分。
使用此來動態添加元素:
$$(document).on('click', '.test', function () {
myApp.alert("Gotcha!");
});
所有答案都不錯。 但是,如果您將此類“測試”用於頁面的其他元素,則最終會引發一些額外的click事件(當您單擊同一類的任何其他元素時)。 因此,如果您想避免這種情況,則應將偵聽器添加到該特定元素。
如果要將類test
的元素添加到id為testId
的現有元素,則使用
$('#testId').on('click', '.test', function(this){
}
在動態添加新元素的函數中,必須為其分配事件處理程序。
假設您有一個類似這樣的功能
function addNewLines(){
//add the new lines here
// you have to run this again
$$('.test').on('click', function () {
myApp.alert("Gotcha!");
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.