[英]Building html from an ajax call to jquery UIs sortable list
我在HTML / JavaScript中遇到設計問題。
我將可排序的jQuery UI附加到了我的Web應用程序:這是一個可排序的演示(現在不能顯示我的應用程序): http : //jqueryui.com/demos/sortable/default.html
現在,使用來自ajax調用的數據在JavaScript中填充該拖放列表。 該列表始終由用戶更改。
我嘗試做這樣的事情:
Var htmlData = '<div id=wrapper>'
+'<div>'
+data.title
+'</div>'
+'<div>'
+data.description
+'</div>';
${"#sortable-list"}.html(htmlData);
等等。 一些div也有在變量中設置的屬性,例如'id="' + data.id + '"'
然后,我嘗試將此字符串htmldata放入sortable-list中。 但是很快變得混亂了。 我試圖在其中放入<tables>
在<p>
加入<span>
。但是,仍然很難獲得我想要的設計。
由於缺乏聲譽而無法張貼圖片,但這是我想要的設計(這只是<li>
中的一個<li>
<ul>
):
那么,您將如何做呢? 我一直在閱讀有關胡須之類的模板的信息,但似乎對我沒有幫助。 而且我用字符串構建表的方法不是最好的方法。
任何有關如何執行此操作的示例或信息都非常感謝
你可以做這樣的事情。
var items[]
items.push($('<div />', { html: data.title }));
items.push($('<div />', { html: data.description}));
$("#sortable-list").html($('<div />', {
'id' : 'wrapper',
'class' : 'yourclass',
html: items.join('')
})
);
您可以在循環中使用items.push
循環所有數據並將項目推入數組。 稍后將數組項加入html
客戶端誘使有很多優點,但是主要的優點是您不必在JavaScript中將HTML串在一起。 這樣做不僅容易出錯,而且很快就會成為維護的噩夢。
例如,這是通過Underscore.js誘人的方法來滿足您的要求的方法。
如您所見,HTML布局清晰,隨着需求的變化將易於更改。
<script type="text/template" id="sortable-entry">
<% _.each(items, function(item) { %>
<div>Title: <%= item.title %></div>
<div>Description: <%= item.description %></div>
<hr />
<% }); %>
</script>
<ul id="sortable-list"></ul>
<script>
var data = {
items: [
{ title: 'title1', description: 'description1' },
{ title: 'title2', description: 'description2' },
{ title: 'title3', description: 'description3' },
{ title: 'title4', description: 'description4' },
{ title: 'title5', description: 'description5' }
]
};
var event_html = _.template($('#sortable-entry').html());
$(event_html(data)).appendTo($('#sortable-list'));
</script>
這是一個實時示例-http://jsfiddle.net/tj_vantoll/kmXUr/ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.