2013-02-25 56 views
3

屬性我有一堆的數據元素的屬性:

<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)代表一切嗎?

$(this).get(0).outerHTML; 

你可以這個插件,如果必要的話:

回答

2

您需要的元素的 「outerhtml」。有些瀏覽器可以通過.outerHTML屬性提供。

做不到這一點,有一個在my answer這一個簡單的插件,一個相關的問題:

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

您可以通過JavaScript和做到這一點很容易

$.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])); 
} 
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() 
0

使用這個.. 。

$('#mydiv').on('click', function(){ 
    console.log(this.outerHTML); 
}); 

看到這個Example