使用 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
Using jQuery to 'click' a li element
提问by Zabs
I have a <ul>
element that dynamically generates the <li>
elements and simply want to run a onclick
event
我有一个<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).ready
block 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
回答by Tushar Gupta - curioustushar
回答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;
});