开发者

jquery click once, then disable/enable element

开发者 https://www.devze.com 2022-12-08 04:18 出处:网络
i have many rows List item - delete List item - delete List item - delete like above 3 rows..it has delete link, on click i want to disable that link, until i get response from ajax saying ok dele

i have many rows

  1. List item - delete
  2. List item - delete
  3. List item - delete

like above 3 rows.. it has delete link, on click i want to disable that link, until i get response from ajax saying ok delete it or no not ok, dont delete it, user is not an owner, then i have to give the element back to clickable.. if that makes sence

开发者_StackOverflow中文版

basically preventing element on click and then restoring its element on error from backend.

what methods do i need to use for this? im using live method, if i use die, then how will i restore again?


As requested, here's a version that uses links instead of buttons.

<ol>
    <li id="item-1">List item <a href="delete.php?1">Delete</a></li>
    <li id="item-2">List item <a href="delete.php?2">Delete</a></li>
    <li id="item-3">List item <a href="delete.php?3">Delete</a></li>
</ol>

And the JS support for this would be

$("ol").click(function(evt){
    if (evt.target.nodeName != "A") {
        return true;// it's not the delete link, so we don't have to do anything
    }
    var listItem = $(evt.target.parentNode);
    if (listItem.hasClass("disabled")) {
        return true;// we're still processing this already deleted list item
    }
    listItem.addClass("disabled");// lock the list item (perhaps visually too)

    // set up the AJAX call
    $.post("evaluator.php", {listId : listItem.attr("id")}, function(data){
        // let's suppose that we get "1" if the user can perform the procedure
        if (data == "1") {
           // request approved, remove the list item
           listItem.fadeOut("fast", function(){
               $(this).remove();
           });
        } else {
            // release the lock
            listItem.removeClass("disabled");
            // request denied, rollback
            alert("Sorry, you can't do that.");
        }
    });
    // here we stop the click event, so the URL in href won't be called.
    // you can "disable" a link by returning false on a click event
    // e.g. <a href="url" onclick="return false">disabled link</a>
    return false;
});


The best way would be to create a separate function to handle the AJAX call, so you could do

$(".delete").bind("click", deleteItem);

And in your deleteItem function you could unbind that by doing

function deleteItem(delBtn) {
    $(delBtn).unbind("click", deleteItem);
    //ajax call
    onerror: function() {
        $(delBtn).bind("click", deleteItem);
    }
}

edit: Realized you're using live, which is just another version of bind. So in the above example you can just switch the bind keyword for live, and unbind for die. And it should do the same (:

0

精彩评论

暂无评论...
验证码 换一张
取 消