简体   繁体   中英

jquery Onclick Function with Callback Sorting Function Causing Double Click

I have a function that appends an item between two lists. Additionally I also have the todo list sorted alphabetically with a function, hence when an item is moved back to the todo list, it will be alphabetically re-ordered.

The issue is that because I have to re-assign the onclick event listener during the sorting, the onclick function creates a loop of the clicking event - this is backed up by console log showing two click events. This causes the link to break as the double click means that the task item cannot append to the other id.

I've tried everything but to no avail - using callback function, using .trigger(), using .triggerHandler(). I'm sure I just need a way to stop the event from firing a second time.

My DOM is as follows:

HTML

<div id="todo">
  <div class="task">
     <div class="c1">B</div>
     <a class="swap" href="JavaScript:void(0);">SWAP</a>
  </div>
  <div class="task">
     <div class="c1">A</div>
     <a class="swap" href="JavaScript:void(0);">SWAP</a>
  </div>
  <div class="task">
     <div class="c1">C</div>
     <a class="swap" href="JavaScript:void(0);">SWAP</a>
  </div>
</div>

<div id="done">
</div>

JAVSCRIPT

// initial $('a.swap').on('click', onClick) is assigned in the AJAX

var onClick = function (event) {
    // code to swap between lists on click of the a link

    // once the item is appended to the other list callback the sort function
    sortByName()
}

var sortByName = function () {
        var sortbyname = $('#todo').find($(".task")).sort(function (a, b) {
            if ($.trim($(a).find(".c1").text()) < $.trim($(b).find(".c1").text())) {
                return -1;
            } else {
                return 1;
            }
        });
        $("#todo").html(sortbyname);
        $('a.swap').on('click', onClick) //this is where the problem seems to be
    }

If you could advise how to stop the onclick event from looping a second time, that would be greatly appreciated.

Many thanks.

在添加新事件之前,请尝试删除当前事件。

$('a.swap').off('click').on('click', onClick);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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