JavaScript:如何将 DOM 元素序列化为稍后使用的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8914985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: how to serialize a DOM element as a string to be used later?
提问by Andrew
This may seem like a strange request, and it is quite out of the ordinary, but it's a challenge that I'm trying to solve.
这似乎是一个奇怪的请求,而且很不寻常,但这是我正在努力解决的一个挑战。
Let's say you have a DOM element, which is made up of HTML and some CSS being applied, and some JS event listeners. I would like to clone this element (and all CSS and JS being applied), serialize it as a string that I could save in a database to be added to the DOM in a future request.
假设您有一个 DOM 元素,它由 HTML 和一些正在应用的 CSS 以及一些 JS 事件侦听器组成。我想克隆这个元素(以及所有应用的 CSS 和 JS),将它序列化为一个字符串,我可以将其保存在数据库中,以便在将来的请求中添加到 DOM。
I know jQuery has a few of these methods (like $.css() to get the computed styles) but how can I do all of these things and turn it into a string that I can save in a database?
我知道 jQuery 有一些这样的方法(比如 $.css() 来获取计算的样式)但是我怎样才能做所有这些事情并将它变成一个我可以保存在数据库中的字符串?
Update:Here is an example element:
更新:这是一个示例元素:
<div id="test_div" class="some_class">
<p>With some content</p>
</div>
<style>
#test_div { width: 200px }
.some_class { background-color: #ccc }
</style>
<script>
$('#test_div').click(function(){
$(this).css('background-color','#0f0');
});
</script>
...and maybe a sample serialization:
...也许还有一个示例序列化:
var elementString = $('#test_div').serializeThisElement();
which would result in a string that looks something like this:
这将导致一个看起来像这样的字符串:
<div id="test_div"
class="some_class"
style="width:200px; background-color:#ccc"
onclick="javascript:this.style.backgroundColor='#0f0'">
<p>With some content</p>
</div>
so I could send it as an AJAX request:
所以我可以将它作为 AJAX 请求发送:
$.post('/save-this-element', { element: elementString } //...
The above is only an example. It would be ideal if the serialization could look very similar to the original example, but but as long as it renders the same as the original, I would be fine with that.
以上只是一个例子。如果序列化看起来与原始示例非常相似,那将是理想的,但只要它呈现与原始示例相同,我就可以接受。
回答by Nitin Jadhav
回答by Raynos
var elem = ...;
var clone = elem.cloneNode(true);
var uuid = get_uuid();
storedElements[uuid] = clone;
storeInDatabase(uuid);
/* some time later */
getFromDatabase(function (uuid) {
var elem = storedElements[uuid];
/* do stuff */
});
回答by emanuelpoletto
I've got a piece of code from an example of http://api.jquery.com/jQuery.extend/that I think will help you to get a complete string of your object. I just didn't figure out how to turn it back to an object yet. Anyway, I think it's a beginning. Maybe someone else could complete this answer... or I myself do it later.
我从http://api.jquery.com/jQuery.extend/的示例中得到了一段代码,我认为它可以帮助您获得完整的对象字符串。我只是不知道如何把它变回一个对象。无论如何,我认为这是一个开始。也许其他人可以完成这个答案......或者我自己稍后再做。
First of all, create a complete clone of your element:
首先,创建元素的完整克隆:
var el = $('div').clone(true, true);
Then, the code from api.jquery.com:
然后,来自 api.jquery.com 的代码:
var printObj = function(obj) {
var arr = [];
$.each(obj, function(key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push( next );
});
return "{ " + arr.join(", ") + " }";
};
Finally:
最后:
var myString = printObj($(el).get(0));
回答by LocalPCGuy
I think the easiest thing to use to recreate your HTML object would be a JSON object, so you'd need a function that would return a JSON object, which you could then stringify to store in a DB. Something like the following might point you in the right direction, but it obviously isn't working fully as is, would be pretty dependent on the DOM element and you would have to write the function to deserializeObject as well.
我认为用于重新创建 HTML 对象的最简单的方法是 JSON 对象,因此您需要一个返回 JSON 对象的函数,然后您可以将其字符串化以存储在数据库中。类似下面的内容可能会为您指明正确的方向,但它显然不能完全按原样工作,非常依赖于 DOM 元素,您还必须将函数编写为 deserializeObject。
// NOT TESTED OR WORKING PROPERLY, FOR EXAMPLE ONLY
// htmlObject is a raw HTML DOM element
function serializeObject (htmlObject) {
var objectToStore = {
htmlElement: htmlObject.toString(),
id: htmlElement.id,
attrs: getAttrs(htmlObject) },
css: htmlElement.style.cssText
}
return objectToStore;
}
function getAttrs(htmlObject) {
var tmp = [], i;
for (i = 0, i<htmlObject.attributes.length; i++) {
tmp.push({htmlObject.attributes[i].nodeName: htmlObject.attributes[i].value});
}
return tmp;
}
回答by Rob Whelan
See https://github.com/ZeeAgency/jquery.htmlize-- this approach seems to work well in my tests, though I'm going to have to hack it up a bit to get it to work in IE6.
请参阅https://github.com/ZeeAgency/jquery.htmlize- 这种方法在我的测试中似乎运行良好,尽管我将不得不对其进行一些修改才能使其在 IE6 中工作。
回答by Kin
Does this makes any sense if using jQuery?
如果使用 jQuery,这是否有意义?
$(this).serialize()
For example visit:
例如访问: