returning clicked li class in an ul javascript/jquery

[亡魂溺海] 提交于 2019-12-01 12:40:44

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

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/

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

edit: jsfiddle link

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

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

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

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