在ul javascript / jquery中返回单击的li类 [英] returning clicked li class in an ul javascript/jquery

查看:119
本文介绍了在ul javascript / jquery中返回单击的li类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码(html页面):

My code (the html page):

<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>  

背后的javascript / jquery:

The javascript/jquery behind it:

$(function () {
    $("ul").click(function () {
        // here I want to get the clicked id of the li (e.g. bakkerLink)
    });
});

我该怎么做?

推荐答案

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

另一种方法是将事件绑定到 li 而不是 ul

Another method is to bind the event to li instead of 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);
    });
});

这篇关于在ul javascript / jquery中返回单击的li类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆