如何在Prototype中使用HTML创建元素? [英] How to create element from HTML in Prototype?
问题描述
有没有一种方法可以在Prototype中使用HTML创建元素,这与jQuery的 $('< div> Foo< / div>)
类似?
基本上,我从Handlebars模板创建HTML块,并希望插入到DOM中,但不想将其包含在其他元素中。
$ b
有没有一种方法可以在Prototype中使用HTML创建元素,这与jQuery的 $('< div> Foo< / div>)
类似?
基本上,我从Handlebars模板创建HTML块,并希望插入到DOM中,但不想将其包含在其他元素中。
$ b
我不相信Prototype有任何内置解决方案。我使用隐藏的textareas来保存我的模板代码,因此 $ 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屋!