简体   繁体   中英

JQuery: Convert onClick attribute to to jQuery click

I have a webpage with 100+ hyperlinks that all have the onClick and href attribute set. This works for the most part but I've run into the issue where browsers like IE7 use the href attribute over the onClick attribute. I need the onClick attribute to be the default so my function will load on click. I figured I could easily do this using jQuery and setting the click event to the onClick attribute value but I'm not having any luck, how would I go about this? Right now the code below sets TONS of click events to a single hyperlink. When I click a hyperlink I can watch the GET events sent multiple times for the hyperlink.

    $("a[href*='/RightSizeOption/NewForm.aspx']").click(function() {
        OpenPopUpPage($(this).attr('href'), RefreshPage); 
        return false;
    });

Doesn't seem to make sense, unless that exact click handler is actually being bound multiple times. A better way of binding clicks is with delegate (also using preventDefault instead of return false for good measure):

$('#myParent').delegate("a[href*='/RightSizeOption/NewForm.aspx']", "click", function(event) {
  event.preventDefault();
  OpenPopUpPage($(this).attr('href'), RefreshPage); 
});

#myParent is any ancestor element that is not expected to get destroyed; could be a wrapper div or 'body' even, though it's better to pick the closest common ancestor that never gets destroyed.

But what worries me is the multiple binding; if your sample code is within a function, that function is being fired multiple times, for example.

I'm also not certain about the "RefreshPage" that you're passing to OpenPopUpPage. I'd have to see what OpenPopUpPage does to even hazard a guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM