简体   繁体   中英

Alert ID of element when clicked

I'm trying to figure out how to display this span's ID in an alert when the span is clicked. More specifically, I need it to display "Movie" so that I can select spans by "Movie" later on.

How can this be achieved? Thank you.

http://jsfiddle.net/neowot/x4yfracg/2/

HTML

<div id="Movie" class="Fun">

    <div class="lister">
        <ul class="active"><span>Rodeo</span></ul>
    </div>

</div>

CSS

.lister ul span {
    cursor:pointer;
}

JS

$(document).ready(function() {

    $(document).on('click', '.lister ul span', function(event) {  
            alert( $(this).attr('id') );
    }); 

}); 

Use closest searching for ".Fun" on ancestors in the DOM tree:

$(document).on('click', '.lister ul span', function(event) {  
        alert( $(this).closest(".Fun").attr('id') );
}); 

http://jsfiddle.net/x4yfracg/5/

More information about closest() function: https://api.jquery.com/closest/

Try like this

$(document).on('click', '.lister ul span', function(event) {  
    console.log( $(this).closest("div").parent().attr("id"));
}); 
$(document).ready(function () {

    $(document).on('click', '.lister', function (event) {
        alert($(this).find('span').attr('id'));
        alert($(this).parent().attr('id'));
    });

});

FIDDLE

First put an attr id to span. What you can do is put the click event to class lister then get the id of the span found inside of that class.Then use .parent() to get its parent and you can now get the parents id as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM