How to create click event for specific link in a jQuery listview.

后端 未结 6 509
北荒
北荒 2020-12-07 06:08

I\'m trying to create a function that starts when you click on a specific link in a listview. The issue is that event doesn\'t seem to fire when you click the link. The lis

相关标签:
6条回答
  • 2020-12-07 06:27

    The issue is you are adding the click listener after you have created the list. When you first create the listener there is nothing for it to listen to. You need to add the on click event after you add the <li>

    0 讨论(0)
  • 2020-12-07 06:30

    Something like this:

    $(function() {
       $("#listviewForLastTenCalls li").on('click', function() { alert('clicked');  });
    });
    
    0 讨论(0)
  • 2020-12-07 06:31
    $('#listviewForLastTenCalls li a').click( function () {
     // code
    });
    
    0 讨论(0)
  • 2020-12-07 06:35

    I hope this is not your fully markup,...

      <label for="listviewForLastTenCalls">Last Ten Calls:</label>
        <ul data-role="listview" id="listviewForLastTenCalls">
        </ul>
    
    <script>
       $('#listviewForLastTenCalls li').click(function(){
            //alert('click event handler fired');
       }); //<--
    </script>
    

    And if the list is creadted dynamically, you have to attach the event, after list was created...

    0 讨论(0)
  • 2020-12-07 06:39

    You have to do event delegation for dynamically added elements.

        $('"#listviewForLastTenCalls"').on("click",'li' ,function(){
           alert('triggered');
        });
    

    And why on() works ??

    Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

    0 讨论(0)
  • 2020-12-07 06:44

    Demo

    <ul data-role="listview" id="listviewForLastTenCalls">
      <!-- items dynamically generated -->
    </ul>
    

    JS

    $(document).on('click', '#listviewForLastTenCalls li a', function () {
     // code
    });
    
    0 讨论(0)
提交回复
热议问题