使用jQuery启用/禁用元素的点击事件

6
我想启用/禁用元素上的点击事件。 我有以下代码...
HTML:
<a id="CP" style="cursor: pointer; text-decoration: underline;">Current Processes</a>

jQuery:

$(document).on("click", "#CP", function(event) {
    $this = $(this);
    $this.click(function() {
        return false;
    });
    $this.html("Processing...").css({
        "text-decoration": "none",
        "cursor": "default"
    });
    $.ajax({
        type: 'post',
        url: 'abc.jsp',
        success: function(process) {
            //My code goes here...
            $this.on("click"); //  Here i want to bind or add handler which is fired previously.
        }
    });
});

设置 href="#" 并移除 cursor: pointer。你正在使用 anchordiv 一样。 - steo
你为什么想要这样做?是因为你只想注册一次事件吗?如果是这种情况,那么你可以使用 one 事件。http://api.jquery.com/one/ - Qpirate
6个回答

15

如果我理解正确,你可以通过以下方式轻松实现:

$this.html("Processing...").css({
    "cursor": "wait",
    "pointer-events": "none"
});

1
非常感谢。 - Imran Mohammed

7

在执行 AJAX 请求时添加一些类,完成后删除。如果链接具有此类,则不执行任何操作。

$(document).on("click", "#CP", function(event) {
    event.preventDefault();
    $a = $(this);
    if($a.hasClass('disabled')) {
        return false;
    }

    $a.html("Processing...").addClass('disabled');
    $.ajax({
        type: 'post',
        url: 'abc.jsp',
        success: function(process) {
            $a.removeClass('disabled');

            // restore inner HTML here
        }
    });
});

0
也许在使用JavaScript提交表单时,您会遇到一个常见问题,即如果多次单击提交按钮,则表单数据将被多次提交。要解决此问题,您只需要借助CSS编写一行代码即可。
document.getElementById("form1").style.pointerEvents="none";

0
var eventhandler = function() {

    $(document).unbind("click");
    $this.html("Processing...").css({
        "text-decoration": "none",
        "cursor": "default"
    });
    $.ajax({
        type: 'post',
        url: 'abc.jsp',
        success: function(process) {
            //My code goes here...
            //Here i want to bind or add handler which is fired previously.
            $(document).click(eventhandler); 
        }
    });
}


jQuery(document).click(eventhandler);

0

$this.on("click") - 这实际上是:"将 click 处理程序绑定到 $this,但不执行任何操作"

要触发事件,请使用:$this.click()$this.trigger("customEvent")


0
也许你应该使用 bind("click"),这样你也可以解除绑定。例如:$("#CP").bind("click",function(){..要运行的函数 // 禁用 CP 的点击事件 $("#CP").unbind("click"); });。祝好运!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接