简体   繁体   中英

jQuery with uncomplete DOM elements

My problem is related to jQuery and the DOM elements. I need a template like the following:

var threadreply = " <li class='replyItem'>"
                + "     <div class='clearfix'>"
                + "         ${tittle}"
                + "     </div>"
                + " </li>"
                ;
$.template( "threadreply", threadreply );

As you can see, this is a list element. My problem is when I parse it with $.tmpl , which retrieves a valid DOM element without the <li> </li> tags.

liElement = liElement + $.tmpl("threadreply", {"tittle": "hello"} ).html();

Is there any way I can retrieve the element without reformatting?

I know I can do it with a template with a valid ul tag and inside an each jQuery template loop, but I'm not working with JSONs, I can't convert my data structures to JSON.

The full example is as follow:

var threadreply = " <li class='replyItem'>"
                + "     <div class='clearfix'>"
                + "         ${tittle}"
                + "     </div>"
                + " </li>"
                ;
$.template( "threadreply", threadreply );

var liElement = "";
for( var i = 0; i < 150; i ++ ){
    liElement = liElement + $.tmpl("threadreply", {"tittle": "hello"} ).html();
}
$(liElement).appendTo("#ULElement");

EDITED

I found a workaround with this thread: JQuery Object to String wich consists on wraping each DOM element returned by the $.tmpl in a div before get the .html() of the object:

liElement = liElement + $('<div>').append( $.tmpl("threadreply", {"tittle": "hello"} )).html();

With 300 elements it takes aprox 290ms in process all elements. With the appendTo() inside the loop, it takes more than 800ms.

you do not get the 'li' element because when you do

liElement = liElement + $.tmpl("threadreply", {"tittle": "hello"} ).html();

you get the contained html (or innerhtml) of the 'li' element.

html:

<ul id="titleList">
</ul>

js:

$.tmpl("threadreply", {"tittle": "hello"}).appendTo('#titleList');

You just need the string and not a real DOM element. Just use:

liElement = liElement + $.tmpl("threadreply", {"tittle": "hello"});

Outside the loop, you need to wrap the HTML you just generated into a new element, and then replace the former li :

$('<li />').html(liElement).replaceAll('li#existingLiID');

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