views:

77

answers:

5

I am attempting to dynamically create the following using data from an array

<li><a href="#" class="red" id="5"><span>Some text</span></a></li>

At the moment, I'm creating it in a rather simple way

var link = '<li><a href="#" class="' + this.cssClass + '" id="' + this.id + '"><span>' +   this.text + '</span></a></li>';
$('#options').append(link);

Although I need a function to be run when the link is clicked, how is the best way to do this?

A: 

Try this:

$(link).find('a').click(clickHandlerFunction).end().appendTo('#options');
noah
+1  A: 
// 1. create jquery object from your html
var $li = $(link);

// 2. bind <a> element's click event
$("a", $li).click(function(){
   // your code or a function
});

// 3. place <li> somewhere in html
$("body").append($li);
Anwar Chandra
+3  A: 
$('<a>').attr({
    id: this.id,
    href: '#'
}).addClass(this.cssClass).click(function() {

     // click event

}).html('<span>' + this.text + '</span>')
  .appendTo($('<li>').appendTo('#options'));
David
A: 

The way you are building the string is fine (though it might not look as nice as using all the jQuery functions) and will actually perform faster than simply using all the jQuery helper functions. How to do it all in one fell swoop is like this:

$('<li><a href="#" class="' + this.cssClass + '" id="' + this.id + '"><span>' + this.text + '</span></a></li>')
    .appendTo('#options').find('a').click(function(e){
      // Handle click
      e.preventDefault();
    });
Doug Neiner
+2  A: 

What I like to do in these situations is create a hidden "template" element on the page that I clone for each element in the array

<li id="template"><a href="" class="" id=""><span></span></a></li>

then looping through your array and adding these elements

$(arr).each(function(i){
    MyObject obj = arr[i];
    var $li = $("#template").clone().removeAttr("id");
    $("a", $li).attr("id", obj.id).addClass(obj.cssClass);
    $("span", $li).text(obj.text);
    $("ul").append($li);
});

forgot the link binding portion!!

$("ul li a").live("click", function (){
    // DO WORK
});

That should bind all of your "a"-click events forever and ever

hunter
this is useful - thanks for sharing. you can replace arr[i] with 'this'
mkoryak
thanks! You could add a #template { display: none; } css class but I think the prefered method would be to $(document).ready(function(){ $("#template").hide(); });
hunter