jQuery click event not working after adding class

前端 未结 7 1610
臣服心动
臣服心动 2020-11-22 01:47

In my JSP page I added some links:

Organization Data


        
相关标签:
7条回答
  • 2020-11-22 02:29

    Since the class is added dynamically, you need to use event delegation to register the event handler

    $(document).on('click', "a.tabclick", function() {
        var liId = $(this).parent("li").attr("id");
        alert(liId);        
    });
    
    0 讨论(0)
  • 2020-11-22 02:30

    on document ready event there is no a tag with class tabclick. so you have to bind click event dynamically when you are adding tabclick class. please this code:

    $("a.applicationdata").click(function() {
        var appid = $(this).attr("id");
    
       $('#gentab a').addClass("tabclick")
        .click(function() {
              var liId = $(this).parent("li").attr("id");
             alert(liId);        
          });
    
    
     $('#gentab a').attr('href', '#datacollector');
    
    });
    
    0 讨论(0)
  • 2020-11-22 02:35

    Here is the another solution as well, the bind method.

    $(document).bind('click', ".intro", function() {
        var liId = $(this).parent("li").attr("id");
        alert(liId);        
    });
    

    Cheers :)

    0 讨论(0)
  • 2020-11-22 02:37

    Based on @Arun P Johny this is how you do it for an input:

    <input type="button" class="btEdit" id="myButton1">
    

    This is how I got it in jQuery:

    $(document).on('click', "input.btEdit", function () {
        var id = this.id;
        console.log(id);
    });
    

    This will log on the console: myButton1. As @Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.

    UPDATE

    Though it would be better to say:

    $(document).on('click', "input.btEdit", function () {
        var id = $(this).id;
        console.log(id);
    });
    

    Since this is JQuery's syntax, even though both will work.

    0 讨论(0)
  • 2020-11-22 02:38

    I Know this is an old topic...but none of the above helped me. And after searching a lot and trying everything...I came up with this.

    First remove the click code out of the $(document).ready part and put it in a separate section. then put your click code in an $(function(){......}); code.

    Like this:

    <script>
      $(function(){
        //your click code
        $("a.tabclick").on('click',function() {
          //do something
        });
      });
    </script>
    
    0 讨论(0)
  • 2020-11-22 02:45

    .live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax

    $(document).on('click', "a.tabclick", function() {
    

    This syntax will work for delegated events

    .on()

    0 讨论(0)
提交回复
热议问题