jQuery:使用off()禁用onclick事件不起作用 [英] jQuery: Disable onclick event using off() not working

查看:343
本文介绍了jQuery:使用off()禁用onclick事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我想要做的一个简单示例,我使用HTML代码,我的目标是禁用三个超链接 #validate #organize #export

 < p id =menuitemsclass =inline textcenter> 
< a id =validatehref =javascript:void(0);的onclick =switchScreen(验证);> VALIDATE< / A> >>
< a id =organizhref =javascript:void(0);的onclick =switchScreen(组织);>组织< / A> >>
< / p>

当我试图调用以下内容时,什么都没有发生。我正在使用jQuery 1.11.4,并且我已经阅读了用于禁用事件侦听器的方法自1.7以来已更改。所以我想知道下面的JavaScript代码是否有错误,或者是一些新的改变:

  $('#validate ').off(' 点击); 
$('#organiz')。off('click');
$('#export')。off('click');


一种方法是将onclick临时设置为null ,但将onclick中的原始元素存储在元素或jquery对象中(例如 data )。使用辅助函数,您可以打开或关闭元素:

 函数setEnabled($ a,已启用){
$ a.each(function(i,a){
var en = a.onclick!== null;
if(en == Enabled)return;
if(Enabled){
a.onclick = $(a).data('orgClick');
}
else
{
$(a).data('orgClick',a .onclick);
a.onclick = null;
}
});
}

可以用类似的方式调用它:

  setEnabled($('#validate'),false); 

(也适用于带有多个元素的jquery对象,因为它们都是)

示例小提琴


Here is a simple example of what I'm trying to do, I have code in HTML and my aim is to disable the three hyperlinks #validate,#organize and #export:

<p id="menuitems" class="inline textcenter">
                        <a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >> 
                        <a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >> 
                        <a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >> 
                        <a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
                    </p>

When I'm trying to call the following, nothing happend. I'm using jQuery 1.11.4 and I've read that the methods for disabling event listeners have changed since 1.7. So I would like to know if there is an error in my JavaScript code below or some new changes:

$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');

解决方案

One way would be to temporarily set the onclick to null, but store the original element onclick in the element or jquery object (e.g. data). With a helper function you can switch the elements on or off:

function setEnabled($a, Enabled ){
    $a.each(function(i, a){          
        var en = a.onclick !== null;        
        if(en == Enabled)return;
        if(Enabled){
            a.onclick = $(a).data('orgClick');            
        }
        else
        {
            $(a).data('orgClick',a.onclick);
            a.onclick = null;
        }
    });
}

Which can be called with something like:

setEnabled($('#validate'), false); 

(also works on jquery objects with multiple elements because of the each)

Example fiddle

这篇关于jQuery:使用off()禁用onclick事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆