How to create element from HTML in Prototype?

一笑奈何 提交于 2019-12-11 11:13:50

问题


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.


回答1:


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();
};


来源:https://stackoverflow.com/questions/11551647/how-to-create-element-from-html-in-prototype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!