Reputation: 397
Apologies if this subject has been hashed through several times, i have read multiple posts on this and also tried out various approaches in jsfiddle.
Basically, i would like to access the content of the lis in the case below i add lis to the ul via a click on a button (in this case the clicks always add the same content- apple, in the real app, the content of each li is different. I would like to be able to click on one li and access the content of that particular li.
The code below gets me to the ul but not the specific li within the ul or the content of that li - any thoughts would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<button id="testfood" type="button">Test</button>
Fruits: <div id="fruits"><ul id="ul_fruits" class="ul_fruits"><li>Fruit test li</li></ul></div> </body>
</html>
This is the JS
<script type="text/javascript">
$(document).ready(function() {
$("#testfood").click(function(event) {
$('#ul_fruits').append("<li><a href='#'>" + "apple" + "</a>" + "</li>");
});
$("#ul_fruits").click(function(e){
console.log("click on #ul_fruits");
alert(this);
var index = $(this).index();
alert("index " + index);
});
});
</script>
Upvotes: 1
Views: 1750
Reputation: 154918
You could use jQuery's event delegation system. Basically, you get the <a>
that was clicked on, and it works automatically for elements you add. Also, the <a href="#">
will navigate which you probably don't want.
// bind it to the <ul>, run when an <a> is clicked inside the <ul>
$("#ul_fruits").on("click", "a", function(e) {
e.preventDefault(); // prevent navigating
var text = $(this).closest("li").text(); // `this` is the <a>; get the text of the <li>
});
Upvotes: 2