I'm making an menu and for that I use jquery to display data.
我正在制作菜单,为此我使用jquery来显示数据。
I want to make it more dynamic and for that I'm using the each()
function
我想让它更具动态性,因为我正在使用each()函数
Here is an representative example of my code http://jsfiddle.net/4r5cLy00/
这是我的代码http://jsfiddle.net/4r5cLy00/的代表性示例
As you can see the on click displays all the listitems of the unordered list and that's not want i want. I want to get the clicked <li>
正如您所看到的那样,单击会显示无序列表的所有列表项,而这不是我想要的。我想点击
I hope someone have a simple solution for this?
我希望有人有一个简单的解决方案吗?
2 个解决方案
#1
2
Do you mean like this?
你的意思是这样的吗?
$(document).ready(function() {
$('ul > li').click(function() {
alert($(this).text());
});
});
#2
0
This is how you'd use event delegation in this instance. It's a good practice and every JS programmer should use it. The advantages are that you only bind one event and you get better performance. Read more here:
这是您在此实例中使用事件委派的方式。这是一个很好的做法,每个JS程序员都应该使用它。优点是您只绑定一个事件,并获得更好的性能。在这里阅读更多:
http://bdadam.com/blog/plain-javascript-event-delegation.html
$('ul').click(function(event) {
if (event.target.tagName == 'LI') {
console.log(event.target.innerText);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
#1
2
Do you mean like this?
你的意思是这样的吗?
$(document).ready(function() {
$('ul > li').click(function() {
alert($(this).text());
});
});
#2
0
This is how you'd use event delegation in this instance. It's a good practice and every JS programmer should use it. The advantages are that you only bind one event and you get better performance. Read more here:
这是您在此实例中使用事件委派的方式。这是一个很好的做法,每个JS程序员都应该使用它。优点是您只绑定一个事件,并获得更好的性能。在这里阅读更多:
http://bdadam.com/blog/plain-javascript-event-delegation.html
$('ul').click(function(event) {
if (event.target.tagName == 'LI') {
console.log(event.target.innerText);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>