将jQuery对象和内容转换为字符串?
我抓住各种jquery对象放入数组,然后吐出为HTML。将jQuery对象和内容转换为字符串?
我想将jQuery对象转换为文本字符串,以便稍后可以将其吐出。
我使用这种技术目前:
console.log($myObject.clone().wrap('<div></div>').html());
然而,只出现被抓住我的对象的内容。
例如,如果$ myObject的是<h2>My Title</h2>
以上仅返回“我的标题”(无H2标签)。
我也尝试使用.text(),但得到相同的结果。
有没有办法将整个jQuery对象转换为文本字符串?
好了,回答我的问题。
console.log($('<div>').append($myObject.clone()).remove().html());
感谢轮到John Feminella在这个线程:
How do you convert a jQuery object into a string?
谁引用了这篇文章:
http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html
你在看什么不是将JQuery对象转换为字符串,而是将DOM节点转换为其HTML表示。
在JQuery中没有内置方法来做到这一点,也没有什么在Javascript中的相似。
这是一个有点乏味,但你可以,但是,重建它。 下面的代码是不完整的,也没有测试,但这里的想法
var h = '';
$('#my_selector').each(function(){
h += '<' + this.NodeName;
for(var k in this.attributes){
h += ' ' + this.attributes[k].nodeName + '="' + this.attributes[k].value + '" ';
}
h += '>';
h += this.innerHTML;
h += '</' + this.NodeName + '>';
});
贝诺克拉波好,也许我没有正确地提出问题。正如你从我的其他答案中看到的,我确实找到了一个解决方案,提供了我正在寻找的东西。但是,谢谢你的信息。我一直在这里学习新的东西。另外,它看起来好像是一个方便的内置功能,可以在将来添加jQuery。我可以看到很多用途。 – 2010-01-04 16:32:09
从你的榜样,你不只是需要使用call $ myObject.html()?
但是,由于我猜你以后可能不仅仅是这样,只是将对象转换为JSON做这项工作?
有几个jQuery插件可以做到这一点。一个我用过的,这一直为我工作不错,似乎并没有被任何更多的,但你可以在这里
http://jollytoad.googlepages.com/json.js
翻遍了jQuery插件库中提供了这些2为可能的替代
http://plugins.jquery.com/project/JSONEncoder
http://plugins.jquery.com/project/LABSJSON
我从来没有尝试任何一方的寿所以不能保证他们是如何有效
console.log($('<div></div>').append($myObject.clone()).html());
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnCreateNewDiv').click(function() {
$('#result').append($('<div></div>').append($('#testClone').clone()).html());
$('#result div:last').show();
});
});
</script>
<style type="text/css">
.Clone
{
background-color: Red;
}
.Clone h1
{
color: Lime;
}
</style>
</head>
<body>
<input type="button" value="Create New Div" id="btnCreateNewDiv" />
<span id="result"></span>
<div id="testClone" class="Clone" style="display: none;">
<h1>
test
</h1>
</div>
</body>
</html>
现场演示请参阅此链接:http://jsfiddle.net/nanoquantumtech/h8WaV/ – Thulasiram 2012-04-24 10:41:51
可能重复:** [jQuery对象到字符串](HTTP://计算器。com/questions/652763)** – hippietrail 2012-10-17 14:42:34