Bhupi
Bhupi

Reputation: 2969

Help in jquery selectors

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

Answers (5)

Felix Kling
Felix Kling

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

profanis
profanis

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

amustill
amustill

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

xzyfer
xzyfer

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

Dr.Molle
Dr.Molle

Reputation: 117314

Use showLi as context:

$("a.showData",showLi).click([...])

Upvotes: 1

Related Questions