【问题标题】:Internet Explorer: Copy/clone children to arrayInternet Explorer:将子项复制/克隆到数组
【发布时间】:2011-04-02 15:15:35
【问题描述】:

从昨天开始我就一直在玩这个问题。我似乎找不到解决办法。

问题:

<ul>
<li>Cats</li>
<li>Dogs</li>
<li>Bats</li>
<li>Ogre</li>
</ul>

希望在文档准备好后使用 javascript/jQuery 将上述无序列表保存到数组中。

使用

someArray = $("ul").children()

在 Internet Explorer 8 中的 $(document).ready() 上,数组将包含 li 元素但没有它们的 innerHTML

会是这样的

<li></li>
<li></li>
...

所以我想我可以将孩子保存到函数 myFunc() 内的全局数组中。这将确保所有内容都已加载。

/* Global Variable */
var someArray = null;

/* function to be called*/
function myFunc() {
   if (someArray == null) someArray = $("ul").children()
   result = someArray with elements from index 0 and n-2
   $("ul").html();

   $.each(result, function() {
       $("ul").append(this)
   }
}

以上代码在 chrome 和 firefox 上完美运行。每次调用 myfunc 时,新的无序列表将只包含猫和狗。

但是,在 IE 上,使用 $("ul").html() 更改无序列表似乎也会更改 someArray。它适用于第一次调用,但在第二次调用时,它将从当前 UL 中提取元素列表

原创元素:猫、狗、蝙蝠、 食人魔第一次访问 IE: 猫、狗、 第二次调用 IE: 空数组

我确实尝试使用 $.extend 克隆数组,但它似乎没有帮助。有没有一种方法可以让我从原始 UL 中保存子节点列表而不让 IE 更改它们?

当我将子节点保存到数组中时,IE似乎使用了指针引用

【问题讨论】:

  • 那是什么语言?因为result = someArray with elements from index 0 and n-2 不是 JavaScript。
  • 只是解释 .. 并不意味着是正确的代码.. 它与从 0 到 n-2 迭代 someArray 相同,因为 n 是数组的长度。 for(i=0; i
  • 但你说 “上面的代码在 chrome 和 firefox 上完美运行......” 你可以明白为什么我认为它是实际代码。

标签: javascript jquery internet-explorer dom


【解决方案1】:

不清楚您实际上要做什么,但是如果您的目标是将这些元素的内容放入数组中,然后清除列表,这是一种方法:

// Grab the animals
var animals = [];
$("ul:first").children().each(function() {
  animals.push(this.innerHTML);
});

// Wipe out the list
$("ul").html("");

// Show the result
var index;
for (index = 0; index < animals.length; ++index) {
  display("animals[" + index + "] = '" + animals[index] + "'");
}

Live example

在该示例中,我只是获取文档中的第一个 ul;显然你会想要使用更合适的选择器。

如果你真的想克隆元素,你可以使用 DOM cloneNode 函数或 jQuery 的包装器 clone

// Grab the animal elements
var animals = [];
$("ul:first").children().each(function() {
  animals.push(this.cloneNode(true));
});

// Wipe out the list
$("ul").html("");

// Show the result
var index;
for (index = 0; index < animals.length; ++index) {
  display("animals[" + index + "] = '" + animals[index].innerHTML + "'");
}

Live example

【讨论】:

    【解决方案2】:

    以更 jQuery-ey 的方式:

    var animals = $("ul").children().map(function(){
          return $(this).text();
    }).get();
    
    alert(animals);
    

    Live example

    我认为您的问题是您的原始代码指向原始列表,而您正在其他地方更改它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      相关资源
      最近更新 更多