如何将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

其他回答

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

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

可以使用jQuery.makeArray(obj)实用函数:

var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];

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

找出HTML节点(对象)可用的属性和方法的最好方法是这样做:

console.log($("#my-node"));

从jQuery 1.6+你可以使用outerHTML包括HTML标签在你的字符串输出:

var node = $("#my-node").outerHTML;

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

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

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>