开发者

How to dynamically build/add list elements (ul, ol, li) using jQuery DOM manipulations?

I am programming an AJAX web page (using IE 8) and need to dynamically build a list in jQuery from the data returned. Later, I will be converting list to jQuery accordian.

I am also trying to开发者_StackOverflow中文版 learn the proper way to use these jQuery functions and chaining. I am just a jQuery NOOB, but understand JavaScript. I found a good article on jQuery dom functions: http://www.packtpub.com/article/jquery-1.4-dom-insertion-methods

I want to add as much as possible using the jQuery dom functions, and jQuery chaining, without resorting to HTML source code using text. I want to mostly use .wrap(), .appendto(), .attr(), .text(), and .parent().

I don't think that the ".attr("class", "CC_CLASS"). is the best way to add a class.

Given the HTML code:

<div id="outputdiv"></div>

Use jQuery dom functions to change it to be the following:

<div id="outputdiv"> 
 <ul id="JJ_ID"> 
  <li> AAA_text </li> 
  <li id="BB_ID"> BBB_text </li> 
  <li class="CC_CLASS"> CCC_text </li> 
  <li id="DD_ID">DDD_text<br/> 

    <ol id="EE_ID"> 
      <li> FFF_text </li> 
      <li id="GG_ID"> GGG_text </li> 
      <li class="HH_CLASS"> HHH_text </li> 
    </ol> 

  </li> 
 </ul> 
</div>

Some code I figured out (ignoring the spaces in text).

var aObj = $('<li></li>').text("AAA_text")
var bObj = $('<li></li>').attr("id", "BB_ID").text("BBB_text"); 
var cObj = $('<li></li>').attr("class", "CC_CLASS").text("CCC_text");
var dObj = $('<li></li>').attr("id", "DD_ID").text("DDD_text");
var fObj = $('<li></li>').text("FFF_text");
var gObj = $('<li></li>').attr("id", "GG_ID").text("GGG_text"); 
var hObj = $('<li></li>').attr("class", "HH_CLASS").text("HHH_text"); 

Somehow add (fObj + gObj + hObj) into eObj ?

var eObj = `*something*`.attr("id", "EE_ID").wrap(`*something*`);

Somehow add (aObj + bObj + cObj+ dObj + eObj) into jObj ?

var jObj = `*something*`.attr("id", "JJ_ID").wrap(`*something*`);  
jObj.appendTo("#xmlOutputId")


The .append method returns the same container object you called it on -- make use of this to chain methods pleasantly:

var inner_list = $('<ol/>', {id: "EE_ID" })
    .append( $('<li/>', {text: "FFF_text" })
    .append( $('<li/>', {id: "GG_ID", text: "GGG_text" })
    .append( $('<li/>', {"class": "HH_CLASS", text: "HHH_text" });

var outer_list = $('<ul/>', {id: "JJ_ID" })
    .append( $('<li/>', {text: "AAA_text" })
    .append( $('<li/>', {id: "BB_ID", text: "BBB_text" })
    .append( $('<li/>', {"class": "CC_CLASS", text: "CCC_text" })
    .append( 
        $('<li/>', {id: "DD_ID", text: "DDD_text"})
        .append(inner_list)
    );

outer_list.appendTo('#xmlOutputId');

You could actually do the entire thing in a single statement with no vars, but in my opinion that would be getting too ugly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜