开发者

Creating nested elements

开发者 https://www.devze.com 2022-12-16 22:29 出处:网络
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>

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 + '">开发者_JS百科;<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>').attr({
    id: this.id,
    href: '#'
}).addClass(this.cssClass).click(function() {

     // click event

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


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


// 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);


Try this:

$(link).find('a').click(clickHandlerFunction).end().appendTo('#options');


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();
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号