如何将jQuery对象转换为字符串?


当前回答

jQuery在这里,所以:

jQuery.fn.goodOLauterHTML= function() {
    return $('<a></a>').append( this.clone() ).html();
}

返回所有HTML内容:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all

其他回答

jQuery在这里,所以:

jQuery.fn.goodOLauterHTML= function() {
    return $('<a></a>').append( this.clone() ).html();
}

返回所有HTML内容:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all

接受的答案不包括文本节点(未定义被打印出来)。

下面的代码片段解决了这个问题:

var htmlElements = $('<p><a href="http://google.com">google</a></p>↵↵<p><a href="http://bing.com">bing</a></p>'), htmlString = ''; htmlElements.each(function () { var element = $(this).get(0); if (element.nodeType === Node.ELEMENT_NODE) { htmlString += element.outerHTML; } else if (element.nodeType === Node.TEXT_NODE) { htmlString += element.nodeValue; } }); alert('String html: ' + htmlString); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

只需使用.get(0)来获取本机元素,并获取其outerHTML属性:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);

不需要克隆和添加到DOM使用.html(),你可以做:

$('#item-of-interest').wrap('<div></div>').html()
new String(myobj)

如果您想将整个对象序列化为字符串,请使用JSON。