将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();
方法。 如何做到这一点?     
已邀请:
这里有两个选择。您可以尝试使用功能全面的客户端MVC系统。我个人建议您看一下主干,它是简约的,并且非常轻巧,没有渲染/ ui默认值,只有7英镑。 或编写自己的微型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();
    });
}
    
看一下javascript模板。 jQuery在Beta中有一个插件可以完成此任务。这是文档。 有一个非常好的库称为Pure,可让您将模板集成到许多javascript框架中。 当然,Google上有很多与此主题相关的文档     

要回复问题请先登录注册