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

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

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

如果你想对一个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 1.6中,这似乎是一个更优雅的解决方案:

$('#element-of-interest').prop('outerHTML');

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

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