需要.llick的eventlistener,以便动态刷新的按钮可以工作,但是操作会成倍增加 [英] Need eventlistener for .click so that dynamically refreshed buttons work, but actions multiply
问题描述
如果我对数据库进行了更改,我有一个页面,其中一个div:s内容(不是整个页面)刷新/重新加载/更新。
I have a page where one div:s content (not the whole page) refresh/reload/update if I make changes to the database.
此内容包含包含一些文本和按钮的行的表。由于我需要按钮仍然可以使用 .click
,我添加了一个eventListeners。问题是,我第一次按下这个div中的一个按钮应该是这样,但是每次按下其中一个按钮时动作就会增加。
This content contains a table with rows that contains some text and buttons. Since I need the buttons to still work with the .click
I added an eventListeners. The problem is that the first time I press one of the buttons inside this div it's as it should be, but for every time I press one of these buttons the actions multiplies.
就像有太多的eventListeners。但我需要创建它们,以便每个按钮都可以点击。你会如何解决这个问题?
It's like there are too many eventListeners. But I need to create them so that every button is clickable. How would you solve this?
我的大脑告诉我,我需要删除其他的eventListeners(因为每次点击都会创建一个,对吧?)然后触发一个新的一个。但我不知道该怎么做。
My brain tells me that I need to delete the other eventListeners (because one is created every time I click, right?) and then trigger a new one. But I don't know how to do that.
我的代码看起来像下面的代码。所以我第一次按下'编辑'我得到一个'你好'警报,第二次我得到两个'你好'警报,第三次我得到三个'你好'警报......等等
My code looks something like the code below. So the first time I press 'Edit' I get one 'Hello'-alert, the second time I get two 'Hello'-alerts, the thirt time I get three 'Hello'-alerts...... etc
HTML
<div class="div-to-reload">
<?php
// Loop Through Database {
echo '<td><p>Some Info</p></td>';
echo '<td><button class="edit-button">Edit</button></td>';
}
?>
</div>
JS
$(document).ready(function(){
var setupEventListener {
$('.edit-button').click(function(e){
e.preventDefault();
someFunction();
});
}
function someFunction(){
// update database with ajax and on success:
alert('hello');
$('.div-to-reload').load(document.URL + ' .div-to-reload', setupEventListeners);
}
setupEventListener();
});
推荐答案
您可以尝试更换
var setupEventListener {
$('.edit-button').click(function(){
e.preventDefault();
someFunction();
});
}
有这样的东西
$(".div-to-reload").on('click', '.edit-button', function(e){
e.preventDefault();
someFunction();
});
);
这样你就可以为所有按钮设置一个处理程序。
这是未经测试但应该有效。
this way you will have a single handler for all buttons. This is not tested but should work.
这篇关于需要.llick的eventlistener,以便动态刷新的按钮可以工作,但是操作会成倍增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!