最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery disable function - Stack Overflow

programmeradmin2浏览0评论
function myfunction(){
    $('button').click(function(){
        alert();
    });
}

myfunction();

$('#x').off('click', myfunction);//click disable myfunction();

<button></button>
<span id='x'></span>

I need to disable function, I have try jquery off, but its not working

can anyone tell me how? and how to enable again?

function myfunction(){
    $('button').click(function(){
        alert();
    });
}

myfunction();

$('#x').off('click', myfunction);//click disable myfunction();

<button></button>
<span id='x'></span>

I need to disable function, I have try jquery off, but its not working

can anyone tell me how? and how to enable again?

Share Improve this question edited Sep 21, 2014 at 20:14 Ben asked Sep 21, 2014 at 20:07 BenBen 2,5648 gold badges39 silver badges63 bronze badges 6
  • 2 What do you want exactly? It is not clear from your description. – Apul Gupta Commented Sep 21, 2014 at 20:09
  • when #x click, disable myfunction() – Ben Commented Sep 21, 2014 at 20:10
  • What is '#x', and which function exactly are you trying to disable? Are you trying to toggle the 'click' handler function? – ne1410s Commented Sep 21, 2014 at 20:11
  • I guess you want when #x clicked, button click should not work? – Apul Gupta Commented Sep 21, 2014 at 20:11
  • yes, #x clicked, myfunction(); will disable – Ben Commented Sep 21, 2014 at 20:12
 |  Show 1 more ment

3 Answers 3

Reset to default 3

What, exactly, do you expect this to do?:

$('#x').off('click', myfunction);

Assuming for a moment that #x is a subset of button, you never actually set myfunction as a handler on button in the first place. You set an anonymous function:

$('button').click(function(){
    alert();
});

If you want to "disable" that function (that is, remove the click handler from your element), then make it a non-anonymous function and remove the handler:

function myfunction () {
    alert();
}

$('button').on('click', myfunction);

$('#x').off('click', myfunction);

Or, if you're just going to do this once and trying to set the handler on all elements except that one, just omit it from your selector:

$('button').not('#x').on('click', myfunction);

Add one variable like isDisabled = false; Check that variable at the begining of the MyFunction(). And set that variable to true when #x clicked.

There is a bug in Internet Explorer with function attr() e prop()... when use disable attribuite.. See here for plete solution: https://lentux-informatica./bug-jquery-disable-e-internet-explorer-soluzione/

发布评论

评论列表(0)

  1. 暂无评论