[英]Representing a div as a Javascript object?
我想在頁面上顯示各種寵物的列表。 每個寵物將鏈接到表示該寵物的javascript對象。 這是我的Pet
類的代碼:
function Pet()
{
var id, name, var color, var photo;
this.getHtml = function()
{
// Should return the html of a div representing the pet.
return html;
}
this.buy = function()
{
//Find out whether pet is for sale, show a buy form, etc
}
// Snip
}
使用此對象,我想這樣做:
var cat = new Pet();
cat.id = 1;
cat.name = 'Cat';
cat.color = 'Black';
cat.photo = 'http://example.com/cat.jpg';
var dog = new Pet();
dog.id = 2;
dog.name = 'Dog';
dog.color = 'White';
dog.photo = 'http://example.com/dog400.jpg';
$(document).append(cat.getHtml());
$(document).append(dog.getHtml());
通過運行此代碼,我想將以下兩個div添加到我的頁面中:
<div id="pet_1">
Pet name: Cat <br>
Color: Black <br>
<img src='http://example.com/cat.jpg' alt='Cat' /><br>
<input type='button' value='Buy This Pet' onclick = 'cat.Buy()';/>
</div>
<div id="pet_2">
Pet name: Dog <br>
Color: White <br>
<img src='http://example.com/dog400.jpg' alt='Dog' /><br>
<input type='button' value='Buy This Pet' onclick = 'dog.Buy()';/>
</div>
我的問題是:
1)編寫pet.getHtml()
函數以使其產生上述輸出的最佳方法是什么? 我真的更喜歡不在javascript的字符串中存儲html,而是希望將div模板存儲在javascript之外的某個地方,並且每次檢索div的html時,都會插入必要的信息,並且html返回新div的代碼。
2)另外,新div中的某些元素(例如“購買”按鈕)應鏈接到產生它們的對象,例如,cat / dog div的“立即購買”按鈕稱為cat.buy();
和dog.buy();
單擊時的方法。
如何做到這一點?
這里有兩個選擇。 您可以嘗試使用功能全面的客戶端MVC系統。 我個人建議您看一下骨干網,它是簡約的,並且具有非常輕巧的View
,沒有呈現/ UI默認值。
或編寫自己的微型MVC系統。
至於視圖,您可以使用諸如EJS或jQuery tmpl之類的模板引擎。
一個EJS視圖將是
<div id="<%= id %>">
Pet name: <%= name %><br>
Color: <%= color %><br>
<img src='<%= url %>' alt='<%= name %>' /><br>
<input type='button' value='Buy This Pet'/>
</div>
然后您的代碼將如下所示:
function render() {
var container = container || $("<div></div>").appendTo(parent);
new EJS({url: view_url}).update(container[0], {
id: this.id,
color: this.color,
url: this.url,
name: this.name
});
var that = this;
container.find(":button").click(function() {
that.buy();
});
}
至於jQuery Tmpl
<script id="petTemplate" type="text/x-jquery-tmpl">
<div id="${id}">
Pet name: ${name}<br>
Color: ${color}<br>
<img src='${url}' alt='${name}' /><br>
<input class="buy" type='button' value='Buy This Pet'/>
</div>
</script>
function render() {
var that = this;
$( "#petTemplate" ).tmpl( [{
id: this.id,
color: this.color,
url: this.url,
name: this.name
}] ).appendTo( parent ).find(".buy:button").click(function() {
that.buy();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.