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


当前回答

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

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

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

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

其他回答

如果你想对一个HTML元素进行字符串化,以便将它传递到某个地方并解析回一个元素,请尝试为该元素创建一个唯一的查询:

// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')

// now 'e_str' is a unique query for this element that can be stringify 
var e_str = e.tagName
  + ( e.id != "" ? "#" + e.id : "")
  + ( e.className != "" ? "." + e.className.replace(' ','.') : "");

//now you can stringify your element to JSON string
var e_json = JSON.stringify({
  'element': e_str
})

than

//parse it back to an object
var obj = JSON.parse( e_json )

//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )

//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();

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

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

这对我来说似乎很有效:

$("#id")[0].outerHTML

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

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

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

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

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