Jquery prepend click handler

无人久伴 提交于 2020-01-30 05:24:28

问题


If you know a better way to do this then please let me know. Right I have a page which will contain lots of buttons, charts and tables. I have read about stopping event propogation and that's what I'll be using. I want to enable help on cerain elements. I have a checkbox which changes the cursor on help enabled divs. What I want to do is prepend a help function before the normal click behaviour.

Basically it's like this.

<input type="button" value="Click me" onclick="alert ('hello')" />

what i want is that if the checkbox is clicked I add a css class (already done) and then I add a click handler before the normal click. When the element is clicked then the helpfunction is run and the default button click handler is not fired. When the help checkbox is unchecked I want to remove the help function. I realise that I could hardocde this for each element and have a check in the helperfunction to see if the checkbox is checked. But I'd prefer a more generic way of doing it.

Thanks

John


回答1:


        $(":button").each(function() {

            // your button
            var btn = $(this); 

            // original click handler
            var clickhandler = btn.attr("onclick");
            btn.attr("onclick", "return false;");

            // new click handler
            btn.click(function() {

                if ($("#chkbox").attr("checked") == true) {

                    // TODO: show your help
                    // TODO: catch event

                }
                else {

                    clickhandler();

                }
            });
        });



回答2:


I think you want to play around with bind/unbind in this case - see http://docs.jquery.com/Events/unbind#typefn

when selecting the checkbox you can bind new click events on your buttons - and unbind them later on.

You will probably also have to work with Event.preventDefault (http://docs.jquery.com/Events/jQuery.Event) in order to suppress the default click behavior if you dont want it

You would use something the likes of:

$("a").bind("click", function(event){
 if ($("#helpcheckbox").attr('checked')
 {
  event.preventDefault();
  // do something
 }
});

Without more code it's hard to be more exact.



来源:https://stackoverflow.com/questions/1264954/jquery-prepend-click-handler

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