Reputation: 1126
hi all i am generating my ul and li as follow and want to fire click event but delegate(),on()and click() method do not work only live() works well but live() is deprecated function so is there any other method that i can use help me pls ??/ here "loadpage" is div present in my html code
<script type="text/javascript">
$(document).ready(function() {
$('#LoadPage').append('<ul class="testul" id="list">');
for (var i = 1; i < 5; i++) {
$('#list').append('<li class="clicks" id="item'+i+'"></li>');
}
$('#LoadPage').append('</ul>');
});
// click event works wtih .live() onlyyy.......................
$('.clicks').live('click', function() {
alert('hello');
});
/*$(".clicks").on("click", function(){
alert('hello');
});
$("#testul").delegate("li", "click", function() {
alert('hello');
});
$("#testul").delegate("li", "click", function() {
alert('hello');
});*/
</script>
Upvotes: 1
Views: 2359
Reputation: 4368
$(document).ready(function() {
$('#LoadPage').append('<ul class="testul" id="list">');
for (var i = 1; i < 5; i++) {
$('#list').append('<li class="clicks" id="item'+i+'"></li>');
}
$('#LoadPage').append('</ul>');
});
// click event works wtih .live() onlyyy.......................
$('.clicks').live('click', function() {
alert('hello');
});
Just change this to
$(document).ready(function() {
$('#LoadPage').append('<ul class="testul" id="list">');
for (var i = 1; i < 5; i++) {
$('#list').append('<li class="clicks" id="item'+i+'"></li>');
}
$('#LoadPage').append('</ul>');
// click event works wtih .live() onlyyy.......................
$('.clicks').click(function() {
alert('hello');
});
});
Previously those <li>
items are not present in DOM, after inserting into DOM, it can have any functionality.
Upvotes: 1
Reputation: 1912
As of jQuery 1.7, the .live() method is deprecated
What version of jQuery are you using? On has been added in version 1.7 look at the documentation here
if you include the right version of jQuery it should work just fine.
and regarding delegate try this one here
Upvotes: 0
Reputation: 2604
The methods delegate(),on()and click() doesn't works because you are not loaded the html yet. Try to define it after you load the li elements.
<script type="text/javascript">
$(document).ready(function() {
$('#LoadPage').append('<ul class="testul" id="list">');
for (var i = 1; i < 5; i++) {
$('#list').append('<li class="clicks" id="item'+i+'"></li>');
}
$('#LoadPage').append('</ul>');
$('.clicks').click(function() {
alert('hello');
});
});
</script>
Upvotes: 1
Reputation: 470
Your selector should match on document since document actually exists. You will then pass on the selector for clicks that will exist. By initially matching on .clicks, your result set is empty and nothing happens.
$(document).on("click", ".clicks", function(){
alert('hello');
});
The documentation for live discusses how to convert code that uses it to use on or delegate: http://api.jquery.com/live/.
Upvotes: 4