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

发布于 2024-07-16 03:20:31 字数 27 浏览 6 评论 0原文

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

How do you convert a jQuery object into a string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

心病无药医 2024-07-23 03:20:31

我假设您需要完整的 HTML 字符串。 如果是这样的话,类似这样的事情就可以解决问题:

$('<div>').append($('#item-of-interest').clone()).html(); 

这有更深入的解释 此处,但本质上您创建一个新节点来包装感兴趣的项目,进行操作,将其删除,并获取 HTML。

如果您只是想要字符串表示形式,请使用new String(obj)

更新

我在 2009 年写了原始答案。截至 2014 年,大多数主要浏览器现在都支持 outerHTML 作为本机属性(例如,请参阅 FirefoxInternet Explorer),因此您可以执行以下操作:

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

I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:

$('<div>').append($('#item-of-interest').clone()).html(); 

This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.

If you're just after a string representation, then go with new String(obj).

Update

I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:

$('#item-of-interest').prop('outerHTML');
黎夕旧梦 2024-07-23 03:20:31

对于 jQuery 1.6,这似乎是一个更优雅的解决方案:

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

With jQuery 1.6, this seems to be a more elegant solution:

$('#element-of-interest').prop('outerHTML');
暮光沉寂 2024-07-23 03:20:31

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

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

Just use .get(0) to grab the native element, and get its outerHTML property:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);
迷鸟归林 2024-07-23 03:20:31

你能说得更具体一点吗? 如果您尝试在标签内获取 HTML ,您可以执行以下操作:

HTML片段:

<p><b>This is some text</b></p>

jQuery:

var txt = $('p').html(); // Value of text is <b>This is some text</b>

Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:

HTML snippet:

<p><b>This is some text</b></p>

jQuery:

var txt = $('p').html(); // Value of text is <b>This is some text</b>
像极了他 2024-07-23 03:20:31

找出 HTML 节点(对象)可用的属性和方法的最佳方法是执行以下操作:

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

从 jQuery 1.6+ 开始,您可以使用 externalHTML 在字符串输出中包含 HTML 标签:

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

The best way to find out what properties and methods are available to an HTML node (object) is to do something like:

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

From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:

var node = $("#my-node").outerHTML;
梦醒灬来后我 2024-07-23 03:20:31

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 is up in here, so:

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

Return all that HTML stuff:

$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all
甚是思念 2024-07-23 03:20:31

这似乎对我来说效果很好:

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

This seems to work fine for me:

$("#id")[0].outerHTML
瘫痪情歌 2024-07-23 03:20:31

接受的答案不涵盖文本节点(打印出未定义)。

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

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>

The accepted answer doesn't cover text nodes (undefined is printed out).

This code snippet solves it:

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>

岁月蹉跎了容颜 2024-07-23 03:20:31

无需克隆并添加到 DOM 即可使用 .html(),您可以执行以下操作:

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

No need to clone and add to the DOM to use .html(), you can do:

$('#item-of-interest').wrap('<div></div>').html()
神回复 2024-07-23 03:20:31

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

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

It may be possible to use the jQuery.makeArray(obj) utility function:

var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];
写下不归期 2024-07-23 03:20:31

如果您想对 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
})

//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();

If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:

// '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();
桃扇骨 2024-07-23 03:20:31
new String(myobj)

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

new String(myobj)

If you want to serialize the whole object to string, use JSON.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文