使用 jQuery 来“点击”一个 li 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19091299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:10:21  来源:igfitidea点击:

Using jQuery to 'click' a li element

javascriptjqueryhtmlonclickdocument-ready

提问by Zabs

I have a <ul>element that dynamically generates the <li>elements and simply want to run a onclickevent

我有一个<ul>动态生成<li>元素的元素,只是想运行一个onclick事件

<ul id="results">
    <li class="device_result searchterm" data-url="apple-iphone-5s">
        <a href="#"> Apple iPhone 5s </a>
    </li>
    <li class="device_result searchterm" data-url="apple-iphone-5c">
        <a href="#"> Apple iPhone 5s </a>
    </li>
</ul>

I've got the following jQuery in a $(document).readyblock but it doesn't seem to work - any ideas what I'm doing wrong?

我在一个$(document).ready块中有以下 jQuery,但它似乎不起作用 - 知道我做错了什么吗?

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

回答by Edorka

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/

尝试小提琴:http: //jsfiddle.net/emPKS/

回答by Sachin

Remove the space in selector

删除选择器中的空格

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

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

并且您还可以使用.on将特定事件附加到匹配的元素

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

Js Fiddle

Js小提琴

回答by Tushar Gupta - curioustushar

Use .on()

使用.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');
});

回答by zzlalani

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

和 Javascrip

function clickFunc(id) {
   console.log('Do something with ' + id);
}

回答by kasper Taeymans

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

回答by Mohsin Shoukat

You can do this without assigning id to ul

您可以在不将 id 分配给 ul 的情况下执行此操作

$('ul').on('click','li.searchterm',function(){
//do your stuffhere;
});