为什么会有两次ajax,为什么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: "<?PHP echo site_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上传了一个帖子.我想它找到了所有“addnew”值(到目前为止有2个,会有更多).如何使用指定的类处理元素?希望这是有道理的.

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

var Classofentry = '';

$('#upload_form option[value="addnew"]').click(function(){

// Show modal window

$('#add-new').modal('show');

// Get the class

var Classofentry = $(this).attr("class");

console.log(Classofentry);Thanks

$('#add-new-submit').on('click',function(){

// Get new option from text field

var value = $('#add-new-text').val();

console.log(value);

$.ajax({

type: "POST",success: success

});

$('#add-new-submit').unbind('click') //

$('#add-new').modal('toggle');

function success(data)

{

//$('#animal_species').append("" + data + "");

$('#'+Classofentry).append("" + data + "");

//alert(data);

//alert('Success!');

}

function errorHandler()

{

alert('Error with AJAX!');

}

});

});