简体   繁体   中英

jQuery: Transform JSON-Object to HTML-List improvements

I have written a function which transforms a multidimensional json-object to an html list: http://jsfiddle.net/KcvG6/

  1. Why does the function render the lists double? Update: http://jsfiddle.net/KcvG6/2/

  2. Are there any improvements about the logic to do?

  3. The original JSON-object generates urls in the url attribute. These urls are generated with a given slug. If the given slug is not yet available (the user hasn't selected anything or what else the link should not be rendered:

     'image': { 'index': { 'name': 'Show all images', 'url': Routing.generate('AcmeImageBundle_Image_index') }, 'new': { 'name': 'Add new image', 'url': Routing.generate('AcmeImageBundle_Image_new') }, 'edit': { 'name': 'Edit selected image', 'url': Routing.generate('AcmeImageBundle_Image_edit', { 'slug': imageSlug }) }, 'delete': { 'name': 'Delete selected image', 'url': Routing.generate('AcmeImageBundle_Image_delete', { 'slug': imageSlug }) } } 

It happens twice because of the call to .children(). You are replacing each child element with the list. Instead, select the first child and replace it.

$(container).children().first().replaceWith(renderList(objectCollection));

http://jsfiddle.net/KcvG6/1/

If you need to remove the <p> element, do that separately.

http://jsfiddle.net/VF2sm/

Assuming you just want to replace the ul in your document, calling .children is not enough. You need to use .find , otherwise it will replace ALL children, of which you currently have 2

$(container).find('ul').replaceWith(renderList(objectCollection));

Or you could easily wipe out the entire contents and repace it with your list like this:

$(container).html(renderList(objectCollection));

As far the quality of your renderList() function, I think its just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM