我正在尝试使用jQuery获取所选对象的HTML.我知道这个.html()
功能; 问题是我需要包含所选对象的HTML(在这种情况下是一个表行,其中.html()
只返回行内的单元格).
我已经四处搜索并发现了一些克隆对象的非常"hackish"类型的方法,将它添加到新创建的div等等,但这看起来真的很脏.有没有更好的方法,或新版本的jQuery(1.4.2)是否提供任何类型的outerHtml
功能?
Eri*_* Hu 662
我相信目前(2012年5月1日),所有主流浏览器都支持outerHTML功能.在我看来,这个片段就足够了.我个人会选择记住这个:
// Gives you the DOM element without the outside wrapper you want
$('.classSelector').html()
// Gives you the outside wrapper as well only for the first element
$('.classSelector')[0].outerHTML
// Gives you the outer HTML for all the selected elements
var html = '';
$('.classSelector').each(function () {
html += this.outerHTML;
});
//Or if you need a one liner for the previous code
$('.classSelector').get().map(function(v){return v.outerHTML}).join('');
Run Code Online (Sandbox Code Playgroud)
编辑:基本支持统计的element.outerHTML
Vol*_*ike 343
无需为其生成函数.就这样做:
$('a').each(function(){
var s = $(this).clone().wrap('<p>').parent().html();
console.log(s);
});
Run Code Online (Sandbox Code Playgroud)
(顺便提一下,您的浏览器控制台将显示记录的内容.自2009年左右以来,大多数最新的浏览器都具有此功能.)
最终的神奇之处在于:
.clone().wrap('<p>').parent().html();
Run Code Online (Sandbox Code Playgroud)
克隆意味着你实际上并没有打扰DOM.没有它运行它你会看到p
在所有超链接之前/之后插入标签(在这个例子中),这是不可取的.所以,是的,使用.clone()
.
它的工作方式是它接受每个a
标记,在RAM中复制它,用p
标记包装,获取它的父项(意味着p
标记),然后获取innerHTML
它的属性.
编辑:提出建议并将div
标签更改为p
标签,因为它的输入较少且工作原理相同.
Dav*_* V. 187
2014年编辑:问题和回复是从2010年开始的.当时,没有更好的解决方案可供广泛使用.现在,许多其他回复都更好:例如Eric Hu,或Re Capcha.
这个网站似乎有一个解决方案: jQuery:outerHTML | Yelotofu
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
Run Code Online (Sandbox Code Playgroud)
Re *_*cha 146
怎么样prop('outerHTML')
?
var outerHTML_text = $('#item-to-be-selected').prop('outerHTML');
Run Code Online (Sandbox Code Playgroud)
并设置:
$('#item-to-be-selected').prop('outerHTML', outerHTML_text);
Run Code Online (Sandbox Code Playgroud)
它对我有用.
PS:这是在jQuery 1.6中添加的.
jes*_*ica 90
扩展jQuery:
(function($) {
$.fn.outerHTML = function() {
return $(this).clone().wrap('<div></div>').parent().html();
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
并像这样使用它: $("#myTableRow").outerHTML();
Tok*_*mon 43
我同意Arpan(2010年12月13日5:59).
他这样做的方式实际上是一种更好的方法,因为你不使用克隆.克隆方法非常耗时,如果你有子元素,并且没有其他人似乎关心IE实际上有outerHTML
属性(是的IE实际上有一些有用的技巧).
但我可能会创建他的脚本有点不同:
$.fn.outerHTML = function() {
var $t = $(this);
if ($t[0].outerHTML !== undefined) {
return $t[0].outerHTML;
} else {
var content = $t.wrap('<div/>').parent().html();
$t.unwrap();
return content;
}
};
Run Code Online (Sandbox Code Playgroud)
And*_*y E 19
要成为真正的jQuery-esque,您可能希望outerHTML()
成为getter 和 setter并使其行为尽可能类似html()
:
$.fn.outerHTML = function (arg) {
var ret;
// If no items in the collection, return
if (!this.length)
return typeof arg == "undefined" ? this : null;
// Getter overload (no argument passed)
if (!arg) {
return this[0].outerHTML ||
(ret = this.wrap('<div>').parent().html(), this.unwrap(), ret);
}
// Setter overload
$.each(this, function (i, el) {
var fnRet,
pass = el,
inOrOut = el.outerHTML ? "outerHTML" : "innerHTML";
if (!el.outerHTML)
el = $(el).wrap('<div>').parent()[0];
if (jQuery.isFunction(arg)) {
if ((fnRet = arg.call(pass, i, el[inOrOut])) !== false)
el[inOrOut] = fnRet;
}
else
el[inOrOut] = arg;
if (!el.outerHTML)
$(el).children().unwrap();
});
return this;
}
Run Code Online (Sandbox Code Playgroud)
这允许我们传递参数outerHTML
,可以是
function (index, oldOuterHTML) { }
- 返回值将成为元素的新HTML(除非false
返回).有关更多信息,请参阅jQuery文档html()
.
MJ *_*ili 16
您还可以使用get(检索与jQuery对象匹配的DOM元素.).
例如:
$('div').get(0).outerHTML;//return "<div></div>"
Run Code Online (Sandbox Code Playgroud)
作为扩展方法:
jQuery.fn.outerHTML = function () {
return this.get().map(function (v) {
return v.outerHTML
}).join()
};
Run Code Online (Sandbox Code Playgroud)
要么
jQuery.fn.outerHTML = function () {
return $.map(this.get(), function (v) {
return v.outerHTML
}).join()
};
Run Code Online (Sandbox Code Playgroud)
多项选择并返回所有匹配元素的外部html.
$('input').outerHTML()
Run Code Online (Sandbox Code Playgroud)
返回:
'<input id="input1" type="text"><input id="input2" type="text">'
Run Code Online (Sandbox Code Playgroud)
SpY*_*3HH 11
要制作一个完整的jQuery插件.outerHTML
,将以下脚本添加到任何js文件中,并在标题中包含jQuery之后:
更新新版本有更好的控制以及更多的jQuery Selector友好服务!:)
;(function($) {
$.extend({
outerHTML: function() {
var $ele = arguments[0],
args = Array.prototype.slice.call(arguments, 1)
if ($ele && !($ele instanceof jQuery) && (typeof $ele == 'string' || $ele instanceof HTMLCollection || $ele instanceof Array)) $ele = $($ele);
if ($ele.length) {
if ($ele.length == 1) return $ele[0].outerHTML;
else return $.map($("div"), function(ele,i) { return ele.outerHTML; });
}
throw new Error("Invalid Selector");
}
})
$.fn.extend({
outerHTML: function() {
var args = [this];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.outerHTML.apply($, args);
}
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
这样您不仅可以获得一个元素的outerHTML,甚至可以同时获得多个元素的Array返回!并且可以在两种jQuery标准样式中使用:
$.outerHTML($("#eleID")); // will return outerHTML of that element and is
// same as
$("#eleID").outerHTML();
// or
$.outerHTML("#eleID");
// or
$.outerHTML(document.getElementById("eleID"));
Run Code Online (Sandbox Code Playgroud)
对于多个元素
$("#firstEle, .someElesByClassname, tag").outerHTML();
Run Code Online (Sandbox Code Playgroud)
console.log('$.outerHTML($("#eleID"))'+"\t", $.outerHTML($("#eleID")));
console.log('$("#eleID").outerHTML()'+"\t\t", $("#eleID").outerHTML());
console.log('$("#firstEle, .someElesByClassname, tag").outerHTML()'+"\t", $("#firstEle, .someElesByClassname, tag").outerHTML());
var checkThisOut = $("div").outerHTML();
console.log('var checkThisOut = $("div").outerHTML();'+"\t\t", checkThisOut);
$.each(checkThisOut, function(i, str){ $("div").eq(i).text("My outerHTML Was: " + str); });
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://rawgit.com/JDMcKinstry/ce699e82c7e07d02bae82e642fb4275f/raw/deabd0663adf0d12f389ddc03786468af4033ad2/jQuery.outerHTML.js"></script>
<div id="eleID">This will</div>
<div id="firstEle">be Replaced</div>
<div class="someElesByClassname">At RunTime</div>
<h3><tag>Open Console to see results</tag></h3>
Run Code Online (Sandbox Code Playgroud)
小智 9
你也可以这样做
document.getElementById(id).outerHTML
Run Code Online (Sandbox Code Playgroud)
其中id是您要查找的元素的id
小智 7
我使用了Jessica的解决方案(由Josh编辑)来使outerHTML能够在Firefox上运行.然而问题是我的代码破坏了,因为她的解决方案将元素包装到DIV中.再添加一行代码解决了这个问题.
以下代码为您提供了外部HTML,使DOM树保持不变.
$jq.fn.outerHTML = function() {
if ($jq(this).attr('outerHTML'))
return $jq(this).attr('outerHTML');
else
{
var content = $jq(this).wrap('<div></div>').parent().html();
$jq(this).unwrap();
return content;
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它:$("#myDiv").outerHTML();
希望有人发现它有用!
// no cloning necessary
var x = $('#xxx').wrapAll('<div></div>').parent().html();
alert(x);
Run Code Online (Sandbox Code Playgroud)
在这里小提琴:http://jsfiddle.net/ezmilhouse/Mv76a/
归档时间: |
|
查看次数: |
444778 次 |
最近记录: |