returning clicked li class in an ul javascript/jquery

让人想犯罪 __ 提交于 2019-12-19 10:54:03

问题


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>  

The javascript/jquery behind it:

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

How do I do that?


回答1:


Use the .on() method with signature $(common_parent).on(event_name, filter_selector, event_listener).

Demo: http://jsfiddle.net/gLhbA/

$(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);
    });
});

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);
    });
});



回答2:


Use jQuery on() instead of click and pass li as selector.

$(function() {
    $("ul").on('click', 'li', function() {
        //Here this will point to the li element being clicked
        alert(this.id);
    });
});

on() reference - http://api.jquery.com/on/




回答3:


$(function() {
    $("li").click(function() {
        alert(this.id);
    });
});

edit: jsfiddle link




回答4:


Handle the click event of the <li> instead of the <ul>.
You can then get this.id.




回答5:


Use the event's target (The anchor that was clicked) and then grab its parent's id:

$(function() {
    $("ul").click(function(e) {
        alert(e.target.parentNode.id);
    });
});

JSFiddle




回答6:


here is one of the way to do. Make sure your using the latest jquery file.

 $("ul li").on('click', function() {
    console.log($(this).attr("id"));
});



回答7:


You may try

$(function () {
    $("li").click(function () {
        var id = $(this).attr("id");
        alert(id);
    });
});

or

$(document).ready( function() {
    $("li").click(function () {
        var id = $(this).attr("id");
        alert(id);
    });
});


来源:https://stackoverflow.com/questions/9726245/returning-clicked-li-class-in-an-ul-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!