Using jQuery to 'click' a li element

后端 未结 6 1812
误落风尘
误落风尘 2020-12-31 08:01

I have a

    element that dynamically generates the
  • elements and simply want to run a onclick event

    
    
            
相关标签:
6条回答
  • 2020-12-31 08:40

    Either do

    $( "li .searchterm" ).on('click', function() {    
       console.log('testing');
    });
    

    OR

    <li class="device_result searchterm" data-url="apple-iphone-5s" onclick="clickFunc(1)">
       <a href="#">Apple iPhone 5s</a>
    </li>
    <li class="device_result searchterm" data-url="apple-iphone-5c" onclick="clickFunc(2)">
       <a href="#">Apple iPhone 5s</a>
    </li>
    

    And the Javascrip

    function clickFunc(id) {
       console.log('Do something with ' + id);
    }
    
    0 讨论(0)
  • 2020-12-31 08:43

    Remove the space in selector

      $("li.searchterm").click(function() {    
       console.log('testing');
    });
    

    and You can also use .on to attach the specific event to the matched elements

      $("li.searchterm").on("click",function() {    
       console.log('testing');
    });
    

    Js Fiddle

    0 讨论(0)
  • 2020-12-31 08:52

    if you add dinamically put the click on the list but select the items:

    $("#results").on("click", ".searchterm", function(event){
        console.log('clicked');
    });
    

    try on the fiddle: http://jsfiddle.net/emPKS/

    0 讨论(0)
  • 2020-12-31 08:54

    Use .on()

    As your content is added dynamically so it is not accessible directly ,So you have to use Event delegation.

    $('#results').on('click','li.searchterm',function() {    
        console.log('testing');
    });
    
    0 讨论(0)
  • 2020-12-31 09:00
    $( "li.searchterm" ).on('click',function() {    
       console.log('testing');
    });
    
    0 讨论(0)
  • 2020-12-31 09:02

    You can do this without assigning id to ul

    $('ul').on('click','li.searchterm',function(){
    //do your stuffhere;
    });
    
    0 讨论(0)
提交回复
热议问题