if you add dinamically put the click on the list but select the items:
$("#results").on("click", ".searchterm", function(event){
console.log('clicked');
});
try on the fiddle: http://jsfiddle.net/emPKS/
문제
I have a <ul>
element that dynamically generates the <li>
elements and simply want to run a onclick
event
<ul id="results">
<li class="device_result searchterm" data-url="apple-iphone-5s">
<a href="#"> Apple iPhone 5s </a>
</li>
<li class="device_result searchterm" data-url="apple-iphone-5c">
<a href="#"> Apple iPhone 5s </a>
</li>
</ul>
I've got the following jQuery in a $(document).ready
block but it doesn't seem to work - any ideas what I'm doing wrong?
$("li .searchterm").click(function() {
console.log("testing");
});
해결책
if you add dinamically put the click on the list but select the items:
$("#results").on("click", ".searchterm", function(event){
console.log('clicked');
});
try on the fiddle: http://jsfiddle.net/emPKS/
다른 팁
Remove the space in selector
$("li.searchterm").click(function() {
console.log('testing');
});
and You can also use .on
to attach the specific event to the matched elements
$("li.searchterm").on("click",function() {
console.log('testing');
});
Use .on()
As your content is added dynamically so it is not accessible directly ,So you have to use Event delegation.
$('#results').on('click','li.searchterm',function() {
console.log('testing');
});
Either do
$( "li .searchterm" ).on('click', function() {
console.log('testing');
});
OR
<li class="device_result searchterm" data-url="apple-iphone-5s" onclick="clickFunc(1)">
<a href="#">Apple iPhone 5s</a>
</li>
<li class="device_result searchterm" data-url="apple-iphone-5c" onclick="clickFunc(2)">
<a href="#">Apple iPhone 5s</a>
</li>
And the Javascrip
function clickFunc(id) {
console.log('Do something with ' + id);
}
$( "li.searchterm" ).on('click',function() {
console.log('testing');
});
You can do this without assigning id to ul
$('ul').on('click','li.searchterm',function(){
//do your stuffhere;
});