[英]How to transform element to string with jQuery
我不需要innerHTML我需要innerHTML 和封閉標簽。 讓我們寫一些例子:
<div id="1" style="qwe"><span class="1"></span></div>
<div id="2" style="asd"><span class="2"></span></div>
<div id="3" style="zxc"><span class="3"></span></div>
我可以通過id獲取元素:
$("#1")
我怎么能得到這樣的字符串:
<div id="1" style="qwe"><span class="1"></span></div>
當然html()不起作用因為它只返回span。
你可以這樣做:
alert( $('#\\31 ').wrap("<div />").parent().html() )
$('#\\31 ').unwrap()
像這樣的東西應該工作正常:
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
var outer = $("#1").outerHTML();
這是一個工作小提琴 。
附加信息
有關原始文章,請訪問http://www.yelotofu.com/2008/08/jquery-outerhtml/ 。
使用這個jQuery插件: https : //github.com/brandonaaron/jquery-outerhtml/blob/master/jquery.outerhtml.js
/*! Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
(function($){
var div;
$.fn.outerHTML = function() {
var elem = this[0],
tmp;
return !elem ? null
: typeof ( tmp = elem.outerHTML ) === 'string' ? tmp
: ( div = div || $('<div/>') ).html( this.eq(0).clone() ).html();
};
})(jQuery);
使用方法如下:
$('#some-element').outerHTML();
您可以在DOM
使用outerhtml
但在JavaScript
使用而不是jQuery
,例如:
var text = document.getElementById('hello').outerHTML;
jsbin代碼演示: http ://jsbin.com/obutul/edit#javascript,html,live
html元素上還有一個outerHTML屬性,它包含所選元素本身。
現在幾乎所有的瀏覽器都實現了outerHTML(包括舊版本的ie - firefox是唯一拖延它的版本,但它已經安排在第11版 ),所以我調整了@James Hill的答案,使用這個本機功能,因為它應該存在更有效率。
jQuery.fn.outerHTML = function(s) {
return this[0].outerHTML ? this[0].outerHTML :
s ? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
var outer = $("#1").outerHTML();
請注意,在outerHTML中存在一些跨瀏覽器的不一致性(例如,在chrome中查看此頁面並與ie進行比較)
您可以將所需的div包裝在另一個div中,然后獲取父div的html。
<div><div id="1" style="qwe"><span class="1"></span></div></div>
<div><div id="2" style="asd"><span class="2"></span></div></div>
<div><div id="3" style="zxc"><span class="3"></span></div></div>
現在,
$("#1").parent().html()
將獲取所需的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.