简体   繁体   中英

How do I figure out which item was selected from a dynamically created list using jQuery

I am dynamically adding items to an ul when a page loads.

addUsersToDropdown = (user_markers) ->
  console.log("inside addUsersToDropdown")
  for marker in user_markers
    console.log("adding name to dropdown , name = #{marker.name}")
    jQuery("#user_list").append("<li><a onclick='return false;' href='#'> <img alt=\"#{marker.name}\" src=\"#{marker.gravatar_url}\" />  #{marker.name}</a></li>")

How do I figure out which item the user selected? Everything I have seen seems to require you know the id before hand. ie

jQuery('#some_id')

Add a click event to every one of your link messages - this will refer to the <a> tag. Which you can use to do what you want with.

$("#user_list a").click(function() {
    // this holds the item that was clicked.
    alert($(this).html());
});

Example: http://jsfiddle.net/KXGtt/

$("$user_list li").click(function() {
    console.log(this.index);
}

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