Reputation: 85
In my HTML
I have ol
and li
this is my HTML
and I have script for those links, like when I click on it i kept a alert to check it its not working
$('#namesId ol li').click(function() {
alert('clicked');
//ToDo
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="col-sm-4" id="namesId" style="padding:0px">
<ol style="padding-left: 10px;">
<li class="v"><a href="">Funny 10 second video! - YouTube (360p)</a></li>
</ol>
</div>
click function id not working what is the problem with it.
Upvotes: 1
Views: 836
Reputation: 4365
Try this:
$('#namesId ol').on('click', 'li', function(e){
e.preventDefault();
alert('clicked');
});
Upvotes: 5
Reputation: 70
You have indicated a name for the selector #namesId, but it's not defined anywhere.
Put it this way and it will work:
<div id="namesId">
<ol style="padding-left: 10px;">
<li class="v"><a href="">Funny 10 second video! - YouTube (360p)</a>
</li>
<li class="v"><a href="">Wildlife</a></li>
</ol>
</div>
Upvotes: 0
Reputation: 437
Below Code working fine.
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ol id="namesId" style="padding-left: 10px;">
<li class="v"><a href="">Funny 10 second video! - YouTube (360p)</a>
</li>
<li class="v"><a href="">Wildlife</a></li>
</ol>
<script>
$('#namesId li').click(function() {
alert('clicked');
//ToDo
});
</script>
</body>
</html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ol id="namesId" style="padding-left: 10px;">
<li class="v"><a href="">Funny 10 second video! - YouTube (360p)</a>
</li>
<li class="v"><a href="">Wildlife</a></li>
</ol>
<script>
$('#namesId li').click(function() {
alert('clicked');
//ToDo
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 72299
As you said li
are generated dynamically, You have to use jQuery event-delegation
So do like below:-
$('#namesId ol').on('click',"li",function(e) {
e.preventDefault();
console.log('clicked');
//ToDo
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4" id="namesId" style="padding:0px">
<ol style="padding-left: 10px;">
<li class="v"><a href="">Funny 10 second video! - YouTube (360p)</a></li>
<li class="v"><a href="">Wildlife</a></li>
</ol>
</div>
Upvotes: 2
Reputation: 112
it should be:
$('#namesId ol li:nth-child(1)').click(function() {
alert('clicked');
//ToDo
}); //for first li click
$('#namesId ol li:nth-child(2)').click(function() {
alert('clicked');
//ToDo
}); //for second li click
Upvotes: 0