将div表示为Javascript对象?
|
我想在页面上显示各种宠物的列表。每个宠物将链接到表示该宠物的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检索到时,都会插入必要的信息,并返回新div的html代码。
2)此外,新div中的某些元素(例如“购买”按钮)应链接到产生它们的对象,例如,cat / dog div的“立即购买”按钮在单击时会调用cat.buy();
和dog.buy();
方法。
如何做到这一点?
没有找到相关结果
已邀请:
2 个回复
蜗仓馈
然后您的代码将如下所示:
至于jQuery Tmpl
捐焦