Reputation: 2969
I want to do something like this:
var showLi = $("<li></li>");
$(showLi).append("<a href='#' class='showData'>Show</a>");
$($ul).append(showLi);
$(showLi+" a.showData").click(function(){
alert("clicked");
});
the above code is giving error when I used the selector for adding click method. What can be other way to do this?
Thanks
Upvotes: 1
Views: 63
Reputation: 816262
You can do like so:
var showLi = $("<li></li>");
$("<a href='#' class='showData'>Show</a>").appendTo(showLi).click(function(){
alert("clicked");
});
$ul.append(showLi);
This avoids searching the element again. showLi
is already a jQuery object, so you should not pass it to $()
again. By the naming of the variable $ul
I assume that its value is a jQuery too. If this is not the case you indeed have to pass it to $()
.
Alternatively, you can create the element with:
$('<a />', {href: '#', class: 'showData', text: 'Show'})
You get the error because you are trying to concatenate an object with a string. If you already have a jQuery object, then you can search for descendants with find()
.
Upvotes: 3
Reputation: 2751
What about this?
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
var showLi = $("<li></li>");
$(showLi).append("<a href='#' class='showData'>Show</a>");
$('#test').append(showLi);
$("a.showData").click(function(){
alert("clicked");
});
});
</script>
<div id='test'></div>
Upvotes: 0
Reputation: 5302
You'll need to use delegate() to bind the event handler, as it's not in the DOM upon page load. live() will also work, but delegate is more efficient.
Here's an example: http://jsbin.com/araqe3/edit
Upvotes: 2
Reputation: 14125
Try this:
var showLi = $("<li></li>");
$(showLi).append("<a href='#' class='showData'>Show</a>");
$($ul).append(showLi)
$("a.showData", showLi).click(function(){
alert("clicked");
});
Upvotes: 0