简体   繁体   English

jQuery:将onClick属性转换为jQuery click

[英]JQuery: Convert onClick attribute to to jQuery click

I have a webpage with 100+ hyperlinks that all have the onClick and href attribute set. 我有一个包含100多个超链接的网页,所有超链接都设置了onClick和href属性。 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. 这在大多数情况下都有效,但是我遇到了一个问题,例如IE7之类的浏览器在onClick属性上使用href属性。 I need the onClick attribute to be the default so my function will load on click. 我需要将onClick属性设置为默认属性,以便在单击时加载我的函数。 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? 我想我可以使用jQuery轻松完成此操作,并将click事件设置为onClick属性值,但是我没有任何运气,我将如何处理? 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. 单击超链接时,我可以观看针对超链接多次发送的GET事件。

    $("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): 绑定点击的一种更好的方法是使用委托(也可以使用preventDefault代替return false以获得良好的效果):

$('#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; #myParent是任何预期不会被破坏的祖先元素; could be a wrapper div or 'body' even, though it's better to pick the closest common ancestor that never gets destroyed. 甚至可以是包装器div或“ body”,尽管最好选择最接近的,不会被破坏的共同祖先。

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. 我也不确定您要传递给OpenPopUpPage的“ RefreshPage”。 I'd have to see what OpenPopUpPage does to even hazard a guess. 我不得不看一下OpenPopUpPage所做的事情,甚至可能会引起猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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