简体   繁体   English

jquery onclick运行两次

[英]jquery onclick runs twice

I have the following javascript when my script is loaded: 加载脚本时,我有以下javascript:

var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
    //removes the hover color from the previous selected
    current_selected_note.removeClass('hover active');
    // sets the currently selected equal to the selected note
    current_selected_note = $(this);
    // adds the hover active to the currently selected
    current_selected_note.addClass('hover active');
    //adds the title of the currently selected to the title input field
    $('#txt_new_note_title').val($(this).find('Strong').text());
    selected_note_id = $(this).get(0).id;
    getNote(selected_note_id);
    load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );

Now AFTER this is loaded i click one of my buttons which has the following javascript: 现在加载后,我点击我的一个按钮,其中包含以下javascript:

    $('#note-item-lists').on('click','.close',function(){
    var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
    if(r == true){
        deleteNote($(this));
       $( "#note-item-lists").find('li').first().click();
    }
})

    function deleteNote(button){
    var id = button.closest('li').get(0).id;
    $.ajax({
        type: 'POST',
        url: '/solo/ajax_delete',
        dataType: 'json',
        data: {
            id: id
        },
        success: function (data) {
        }
    });
    button.closest('li').remove();
}

When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again. 当发生这种情况时(我调试它)并且首先调用事件函数1次(正确地添加类),然后立即再次发生。

Anyone tried this before? 以前有人试过吗?

Try this, It will call one time. 试试这个,它会打电话一次。

 $('#note-item-lists .close').on('click',function(){
          alert("Hello");      
 });

Try using .off() 尝试使用.off()

$('#note-item-lists').on('click', '.list-group-item', function () {
    $(this).off();  //add this here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM