我想在我的页面上显示各种宠物的列表。每只宠物都会链接到代表该宠物的 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()
函数以产生上述输出的最佳方法是什么?我真的不想将html存储在我的javascript中的字符串内,而是更希望模板div可以存储在javascript之外的某个地方,并且每次检索该div的html时,插入必要的信息,以及html返回新 div 的代码。
2) 此外,新 div 中的某些元素(例如购买按钮)应链接到生成它们的对象,例如 cat/dog div 的“立即购买”按钮调用 cat.单击时的 buy();
和 dog.buy();
方法。
如何实现这一点?
最佳答案
这里有两个选项。为此,您可以尝试使用完整的客户端 MVC 系统。我个人建议您查看backbone它很简约,并且有一个非常轻量级的 View
,没有渲染/ui 默认值。
或者编写您自己的微型 MVC 系统。
对于 View ,您可以使用 EJS 或 jQuery tmpl 等模板引擎。
EJS View 是
<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();
});
}
关于javascript - 将 div 表示为 Javascript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5687486/