如何临时安置任意的dom节点 [英] How to temporarily house arbitrary dom nodes

查看:103
本文介绍了如何临时安置任意的dom节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在KnockoutJS中做了一些先进的工作,我在KO进程之外生成一些html,对它们应用绑定,然后将它们插入到我的页面中。



问题是存放新的html。我的html是几行表,当我执行

  var div = document.createElement('div'); 
div.innerHTML = template(viewModel);

div将所有表格内容删除(我的 tr td 标签),大概是因为div不能包含表行。



我的cheesy解决方法现在的时刻如下:使用tbody。但我想要一些更广泛的东西。我想要使​​用一个文档片段,但是似乎没有一个innerHTML属性来设置。



处理这个文件的首选方法是什么?

  var div = document.createElement('tbody'); 
div.innerHTML = template(viewModel);
ko.applyBindingsToDescendants(bindingContext,div);

$(element).after($(div).contents());


解决方案

作为解决方法,您可以获取父类型节点,创建一个这种类型的空的分离的新节点以容纳您的内容,然后从那里获取项目。



可能看起来像这样,假设你不介意在 元素,而不是之后:

  var container = document.createElement(element.parentNode.tagName),
frag = document.createDocumentFragment();

container.innerHTML = template(viewModel);
ko.applyBindingsToDescendants(bindingContext,container);
while(container.childNodes.length){
frag.appendChild(container.childNodes [0]);
}
element.parentNode.insertBefore(frag,element);

但是最好弄清楚为什么你的内容被剥离开始。 >

I'm doing a bit of advanced work in KnockoutJS, whereby I generate some html outside of the KO process, apply bindings to them, and then insert them in my page.

The problem is housing the new html. My html is a couple of table rows, and when I do

var div = document.createElement('div');
div.innerHTML = template(viewModel);

the div strips out all the table content (my tr and td tags), presumably since divs can't contain table rows.

My cheesy workaround for the moment is below: use a tbody. But I'd like something a bit more generalized. I thought to use a document fragment, but that doesn't seem to have an innerHTML property to set.

What's the preferred way to handle this?

var div = document.createElement('tbody');
div.innerHTML = template(viewModel);
ko.applyBindingsToDescendants(bindingContext, div);

$(element).after($(div).contents());

解决方案

As a workaround you could fetch the type of the parent node, create an empty detached new node of that type to house your contents, and later fetch the items from there.

It might look something like this, assuming you don't mind inserting the content before element, rather than after it:

var container = document.createElement(element.parentNode.tagName),
    frag = document.createDocumentFragment();

container.innerHTML = template(viewModel);
ko.applyBindingsToDescendants(bindingContext, container);
while (container.childNodes.length){
    frag.appendChild(container.childNodes[0]);
}
element.parentNode.insertBefore(frag, element);

But it'd be better to figure out why your contents are stripped to begin with.

这篇关于如何临时安置任意的dom节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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