开发者

onclick and jQuery event binding causing pain

I have a link which has an onclick attribute, and there is a toggle event that I bind to the link (I know I'm committing a sin here by mixing these two, but there is nothing I can do about it.)

Now to this background, I have 2 scenarios:

  1. The user clicks on the link - The order of execution of events is :- onclick first, then the toggle event bound via jQuery
  2. Fire the click event via jQuery - The order of e开发者_如何学Cxecution here is different, the bound event fires first then the onclick.

Something goes horribly wrong because of these 2 scenarios and the flipping of the order. I need the bound events to run first before the onclick. Is there any better way to do this than removing the onclick attribute on init and saving them to the link via .data() and then handling through the toggle event?

Another thing that I need to take care of (life is complicated), the link can be toggled through the querystring. i.e. if the user comes in from another page via another link, there will be a querystring parameter with the link id, which is read by another JavaScript function that does scenario 2 mentioned above.

So if the onclick is to be removed, it will have to be done on init.

What can I do to untangle this mess?


What is so wrong to remove the .onclick function and re-bind it afterwards (after you bound all your methods which should fire before) ?

HTML

<div id="foo" onclick="inline();">click me</div>

Javascript

function inline() {
    alert('I was bound through onclick=');
}

$(function() {
    var $foo = $('#foo'),
        stored = $foo[0].onclick;

    $foo[0].onclick = null;

    $foo.bind('click', function() {
        alert('I was bound via jQuery');
    });
    $foo.bind('click', stored);
});

After that code, the order of alerts would be:

'I was bound via jQuery'
'I was bound through onclick='

Demo: http://jsfiddle.net/3MKWR/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜