开发者

jQuery with uncomplete DOM elements

开发者 https://www.devze.com 2023-02-22 17:35 出处:网络
My problem is related to jQuery and the DOM elements. I need a template like the following: var threadreply = \" <li class=\'replyItem\'>\"

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开发者_StackOverflow社区() 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');
0

精彩评论

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

关注公众号