2009-10-08 83 views
2

我有很多行jQuery的点击一次,然后禁用/启用元素

  1. 列表项目 - 删除
  2. 列表项目 - 删除
  3. 列表项目 - 删除

像上面3行..它有删除链接,点击我想禁用该链接,直到我得到了答复从ajax说好吧删除它或没有不好,不要删除它,用户不是一个所有者,那么我必须把元素回到可点击的..如果这使得sence

基本上防止元素点击,然后从后端恢复其元素错误。

我需要使用哪些方法?即时通讯使用现场方法,如果我使用死亡,那么我将如何恢复?

回答

3

按照要求,这是一个使用链接,而不是按钮的版本

<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> 

而且这个JS的支持将是

$("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; 
}); 
+0

它怎么可以与链接而不仅仅是按钮...但你可以通过设置按钮的禁用属性来禁用点击,但不知道如何禁用链接。 – Basit 2009-10-08 11:31:41

+0

我已根据您的要求修改了代码。希望能帮助到你。 – Wabbitseason 2009-10-08 16:25:38

1

最好的方法是创建一个单独的函数来处理Ajax调用,因此你可以做

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

而在你的deleteItem功能,你可以解绑做

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

编辑:意识到您正在使用live,这是bind的另一个版本。因此,在上面的示例中,您可以将bind关键字切换为live,将unbind切换为die。而且它也应该这样做(:

+0

活法..。绑定将不会对阿贾克斯自动behindings有用 – Basit 2009-10-08 10:32:00

+0

绑定/取消绑定工作方式与现场/死亡http://docs.jquery.com/Events/die – peirix 2009-10-08 10:50:20

+0

我明白生活和死亡一样..但如果你打电话死,那么它会杀死所有的元素事件,而不仅仅是单一事件,并且将所有元素事件都放入事件中元素,就像绑定..但只有它继续添加更多的事件在新的元素,后来由ajax添加。 真的死不是这个的解决方案。 – Basit 2009-10-08 11:33:34