0

我有一个 javascript/jquery 函数:

function deleteRecordByClick(){
    $('.deleteRecord').click(function(){
        alert("deleting record");
        var confirmMsg = confirm('Are you sure you want to delete record?');    
        if(confirmMsg){  
            alert(idRecordToDelete);  // fires the correct id to delete
            ajaxDeleteRecord(idRecordToDelete); //my own ajax working properly      
        }               
    });
}

从手风琴集中删除记录。每个手风琴都是动态创建的,并有一个带有“.deleteRecord”类的按钮。现在该函数已正确调用,但是如果我添加 N 条记录,当我单击随机手风琴时,即使显然数据库上的删除仅第一次正确触发,该函数也会被调用 N 次,但我收到 N 条确认消息。我在创建记录时调用该函数:

function addNewAccordion(){
   //.... my code to add accordion with
   // <h3 ... class="deleteRecord">
   deleteRecordByClick(); //here I call the function
}

有没有一种方法可以破坏该功能并重新创建它,或者有什么更好的方法来解决我的问题?谢谢

4

2 回答 2

3

当您每次创建手风琴时运行该函数时,它将向每个先前创建的手风琴添加另一个事件处理程序。

您可以首先创建所有手风琴,然后调用该函数一次,或者您可以将特定手风琴元素的引用发送到每次调用的函数中:

deleteRecordByClick(accordion);

在函数中,您将使用引用来限制您在该手风琴内的搜索:

function deleteRecordByClick(accordion){
  $('.deleteRecord', accordion).click(function(){
  ...
}
于 2012-10-27T09:04:41.060 回答
1

您应该使用事件委托:

$(addedAccordion).on('click', '.deleterecord', function(){/*stuff to delete entry here */})

在 addNewAccordion 中,而不是为手风琴中的每个元素添加一个侦听器。

function addNewAccordion() {
    //.... my code to add accordion with
    // <h3 ... class="deleteRecord">
    // var addedAccordion = ... get a reference to the accordion
    $(addedAccordion).on('click','.deleterecord', function() {
        alert("deleting record");
        var confirmMsg = confirm('Are you sure you want to delete record?');
        if (confirmMsg) {
            alert(idRecordToDelete); // fires the correct id to delete
            ajaxDeleteRecord(idRecordToDelete); //my own ajax working properly      
        }
    });
}
于 2012-10-27T09:11:53.167 回答