LinkButton does not invoke on click()

前端 未结 8 906
不思量自难忘°
不思量自难忘° 2020-12-29 08:15

Why doesn\'t this work?

    
    

        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 09:00

    That's a tough one. As I understand it, you want to mimic the behavior of clicking the button in javascript code. The problem is that ASP.NET adds some fancy javascript code to the onclick handler.

    When manually firing an event in jQuery, only the event code added by jQuery will be executed, not the javascript in the onclick attribute or the href attribute. So the idea is to create a new event handler that will execute the original javascript defined in attributes.

    What I'm going to propose hasn't been tested, but I'll give it a shot:

    $(document).ready(function() {
    
    // redefine the event
    $(".myButton").click(function() {
       var href = $(this).attr("href");
    
       if (href.substr(0,10) == "javascript:") {
          new Function(href.substr(10)).call(this);
          // this will make sure that "this" is
          // correctly set when evaluating the javascript
          // code
       } else {
          window.location = href;
       }
    
       return false;
    });
    
    // this will fire the click:
    
    $(".myButton").click();
    
    });
    

提交回复
热议问题