【问题标题】:retrieve objects own tag [duplicate]检索对象自己的标签[重复]
【发布时间】:2012-04-11 22:22:12
【问题描述】:

我正在使用 jQuery 对 li 标签列表进行排序,我当前的代码是:

var arr = [];
$("ul li").each(function() {
    arr.push($(this));
});
arr.sort(cmpFunction);
$("ul").find("li").remove();
$.each(arr, function(index, item){
    console.log(item.html());
});

我在 console.log 中发现的 - 我正在丢失包含 li 标签的外部(带有我想要保留的 html5 数据属性)

.html() 是否还有另一个选项可以给我对象 li 标记

我在这里提供了一个我需要的简单示例:http://jsbin.com/esalas/5

【问题讨论】:

标签: javascript jquery


【解决方案1】:

jQuery 中没有内置函数可以做到这一点。解决方法是将元素包装在另一个元素中,然后获取该元素的html()

$.each(arr, function(index, item) {
    var html = item.wrap("<div></div>").parent().html();
    console.log(html);
});

您也可以恢复为原生 Javascript 并使用 outerHTML - 虽然我没有对此进行测试:

$.each(arr, function(index, item) {
    console.log(item[0].outerHTML);
});

【讨论】:

  • 一切都好,但 outerHtml() 应该是 outerHTML(不是函数)。
  • item[0].outerHTML 非常感谢
猜你喜欢
  • 2019-06-05
  • 2010-09-23
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 2012-08-06
相关资源
最近更新 更多