为什么jQuery ajax在这里发布两次?

第一次选择“添加新”并添加新选项时,以下工作正常。 第二次(对于按类别区分的不同元素),它将新选项添加​​到所选元素和第一个元素。 这两个元素必然会重新出现。

 $('#upload_form option[value="addnew"]').click(function(){ // Show modal window $('#add-new').modal('show'); // Get the class var Classofentry = $(this).attr("class"); $('#add-new-submit').on('click', function(){ // Get new option from text field var value = $('#add-new-text').val(); console.log(value); $.ajax({ type: "POST", url: "main/change_options", data: {new_option: value, new_option_class: Classofentry}, dataType: "html", error: errorHandler, success: success }); function success(data) { $('#'+Classofentry).append("" + data + ""); //alert(data); //alert('Success!'); } function errorHandler() { alert('Error with AJAX!'); } $('#add-new').modal('toggle'); }); });  

奇怪的是,它似乎两次在ajax上传了一个post。 我想它找到了所有“addnew”值(到目前为止有2个,会有更多)。 如何使用指定的类处理元素? 希望这是有道理的。

谢谢你的回复! 我找到了一种方法来让它工作,让点击嵌套,但解除第二个点击。 我无法得到建议的solns(它不需要所有的function)。 当它们没有嵌套时,似乎没有办法让第二次点击工作。 我不知道为什么。 在调用ajax的函数中也需要成功和errorHandler函数。 这是代码(与上面的问题相同,但在第二次嵌套点击中使用unbind语句):

   

不要嵌套点击事件

这里的问题是,每当你触发$('#upload_form option[value="addnew"]')上的点击事件时,你就会在$('#add-new-submit')上绑定点击事件

您的脚本应如下所示

 var Classofentry; $('#upload_form option[value="addnew"]').click(function () { // Show modal window $('#add-new').modal('show'); // Get the class Classofentry = $(this).attr("class"); }); $('#add-new-submit').on('click', function () { // Get new option from text field var value = $('#add-new-text').val(); console.log(value); $.ajax({ type: "POST", url: "main/change_options", data: { new_option: value, new_option_class: Classofentry }, dataType: "html", error: errorHandler, success: success }); $('#add-new').modal('toggle'); }); function success(data) { $('#' + Classofentry) .append(""); //alert(data); //alert('Success!'); } function errorHandler() { alert('Error with AJAX!'); } 

正确的代码:

 var Classofentry = ''; $('#upload_form option[value="addnew"]').click(function(){ // Show modal window $('#add-new').modal('show'); Classofentry = $(this).attr("class"); // Get the class }); $('#add-new-submit').on('click', function(){ // Get new option from text field var value = $('#add-new-text').val(); console.log(value); $.ajax({ type: "POST", url: "main/change_options", data: {new_option: value, new_option_class: Classofentry}, dataType: "html", error: errorHandler, success: success }); function success(data){ $('#'+Classofentry).append(""); //alert(data); //alert('Success!'); } function errorHandler(){ alert('Error with AJAX!'); } $('#add-new').modal('toggle'); });