如何在Prototype中使用HTML创建元素? [英] How to create element from HTML in Prototype?

查看:93
本文介绍了如何在Prototype中使用HTML创建元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Prototype中使用HTML创建元素,这与jQuery的 $('< div> Foo< / div>)类似?



基本上,我从Handlebars模板创建HTML块,并希望插入到DOM中,但不想将其包含在其他元素中。

$ b

解决方案

$ F()调用。最后3行更具体到你的问题 - 创建一个新的div,插入你的应用模板HTML,然后返回第一个后裔(作为一个元素,在这一点上)。这假设你的模板只有一个根元素。

  Mustache.createElementFromTemplateId = function(templateId,data){
if(!this.cachedTemplates)this.cachedTemplates = {};

var templateStr = this.cachedTemplates [templateId];
if(!templateStr){
templateStr = $ F(templateId);
this.cachedTemplates [templateId] = templateStr;
}

var appliedTemplateStr = this.render(templateStr,data);

var div = new Element(div);
div.insert(appliedTemplateStr);
return div.firstDescendant();
};


Is there a way to create element from HTML in Prototype that's an analog to jQuery's $('<div>Foo</div>')?

Basically I create HTML chunk from a Handlebars template and want to insert into DOM but don't want to wrap it in some other element.

解决方案

I added this function as a 'static method' to Mustache for one of my recent projects to solve the same problem. I don't believe there is anything built-in to Prototype to solve this. I used hidden textareas to hold my template code, hence the $F() call. The last 3 lines are more specific to your problem - create a new div, insert your applied template html, then return the first descendant (as an element, by this point). This assumes your template only ever has one root element.

Mustache.createElementFromTemplateId = function(templateId, data) {
    if (!this.cachedTemplates) this.cachedTemplates = {};

    var templateStr = this.cachedTemplates[templateId];
    if (!templateStr) {
        templateStr = $F(templateId);
        this.cachedTemplates[templateId] = templateStr;
    }

    var appliedTemplateStr = this.render(templateStr, data);

    var div = new Element("div");
    div.insert( appliedTemplateStr );
    return div.firstDescendant();
};

这篇关于如何在Prototype中使用HTML创建元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆