Rid*_*idz 1 javascript jquery listitem
我的代码(html页面):
<nav>
<ul>
<li id="homeLink"><a href="#">Home</a></li>
<li id="rekenLink"><a href="#">Rekenmachine</a></li>
<li id="bakkerLink"><a href="#">Parkeergarage</a></li>
<li id="garageLink"><a href="#">Bij de bakker</a></li>
<ul>
</nav>
Run Code Online (Sandbox Code Playgroud)
它背后的javascript/jquery:
$(function () {
$("ul").click(function () {
// here I want to get the clicked id of the li (e.g. bakkerLink)
});
});
Run Code Online (Sandbox Code Playgroud)
我怎么做?
Rob*_*b W 10
使用.on()带签名的方法$(common_parent).on(event_name, filter_selector, event_listener).
$(function() {
$("ul").on("click", "li", function() {
// here I want to get the clicked id of the li (e.g. bakkerLink)
var id = this.id;
alert(id);
});
});
Run Code Online (Sandbox Code Playgroud)
另一种方法是将事件绑定到li而不是ul:
$(function() {
$("li").click(function() {
// here I want to get the clicked id of the li (e.g. bakkerLink)
var id = this.id;
alert(id);
});
});
Run Code Online (Sandbox Code Playgroud)