Jquery .off and then restore it to on

寵の児 提交于 2019-12-13 03:55:24

问题


When i want to remove the click handler from my submit button,I am using

$(#submitBtn).off();//works fine

But,when I want to restore back to its previous stage,.on() doesnt work.

                if(flag){
               $(#submitBtn).off();//works fine
                $.ajax({
                    type: 'POST',
                    url: 'someservice.php',
                    data: {email:email,name:name,text:text},
                    success: function (data) {
                       $('#submitBtn').on();//does not work
                });//ajax end
            }

回答1:


.off()

Calling .off() with no arguments removes all handlers attached to the elements. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names.

.on()

Attach an event handler function for one or more events to the selected elements. And it must have arguments -

.on( events [, selector ] [, data ], handler )

Instead of binding and unbinding, I suggest you use button disabling logic : .prop('disabled')

$('#submitBtn').prop('disabled',true)         //disable
$('#submitBtn').prop('disabled',false)        //enable

Note : The ID selector is written as $('#submitBtn') and not $(#submitBtn)




回答2:


You are removing the event so when you call on() you need to specify which event since it won't know about it.

$('#submitBtn').on('click', someFn);

You could also disable the button to prevent multiple submits and then remove the disabled attribute in your ajax success handler



来源:https://stackoverflow.com/questions/24502835/jquery-off-and-then-restore-it-to-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!