我有一堆带有数据属性的元素:
<span data-product_attribute="title" data-product_id="12">product title</span>
<span data-product_attribute="vendor" data-product_id="12">product vendor</span>
我正在使用jQuery选择器来抓取它们并将它们放在一个列表中进行处理:
$('span[data-product_attribute]').map(function() {
var o = {};
o.name = $(this).attr("data-product_attribute");
o.value = $(this).html(); // ** this line is not what I want **
return o;
}).get()
html()
方法只返回<span>
标记中包含的内容,但我想要的是整个内容。即我正试图让它做到这一点:
o.value = '<span data-product_attribute="title" data-product_id="12">product title</span>'
是否有一个jQuery方法会返回$(this)
表示的所有内容?
答案 0 :(得分:2)
你需要元素的“outerhtml”。有些浏览器可以通过.outerHTML
属性提供此功能。
如果做不到这一点,my answer中有一个关于相关问题的简单插件:
(function($) {
$.fn.outerhtml = function() {
return $('<div/>').append(this.clone()).html();
};
})(jQuery);
答案 1 :(得分:1)
示例HTML:
<div id="testing">
<span data-product_attribute="title" data-product_id="12">product title</span>
<span data-product_attribute="vendor" data-product_id="12">product vendor</span>
</div>
使用Javascript:
function getHtml(elem) {
var tmp = $('<div />');
tmp.append(elem);
return $(tmp).html();
}
$('span[data-product_attribute]').map(function() {
var o = {};
o.name = $(this).attr("data-product_attribute");
o.value = getHtml($(this));
alert(o.value);
return o;
}).get()
答案 2 :(得分:0)
您可以通过以下方式轻松地通过JavaScript执行此操作:
$(this).get(0).outerHTML;
如有必要,您可以使用此插件:
$.fn.outerHTML = function(){
return (!this.length) ? this : (this[0].outerHTML || (
function(el){
var div = document.createElement('div');
div.appendChild(el.cloneNode(true));
var contents = div.innerHTML;
div = null;
return contents;
})(this[0]));
}
答案 3 :(得分:0)