【问题标题】:DOM appendChild alternateDOM appendChild 备用
【发布时间】:2011-06-12 00:18:39
【问题描述】:

我正在创建一个 DOM 元素,如下所示;

var imgEle = document.createElement('img');
    imgEle.src = imgURL;         
    x.appendChild(imgEle);

现在对于最后一行,而不是每次调用函数时创建多个 img 元素的 append,我希望它被替换或始终是 x.. 的第一个子元素。

我应该如何为跨浏览器兼容性做同样的事情?

【问题讨论】:

    标签: javascript html css dom appendchild


    【解决方案1】:
    var xChildren = x.childNodes;
    if(xChildren[0])
       x.replaceChild(myIMG, xChildren[0]);
    else
       x.appendChild(myIMG);
    

    这应该可以解决问题

    我们正在抓取 X 的所有子元素,然后我们检查它们中的第一个是否已定义。 (如果有多个,您也可以使用 x.innerHTML 方法一次将它们全部删除)。如果它被定义了,我们用我们新创建的元素替换它,如果没有 - 我们简单地追加元素。

    编辑:通过在循环中创建和附加元素,您的脚本有点繁重 - 因为您似乎只想更改 x 中包含的图像,为什么不简单地求助于 . src 属性?

    var xChildren = x.childNodes;
    var myIMG;    
    if(xChildren[0])
       mIMG = xChildren[0]; //you should be sure that this is an image 
       // perhaps you might want to check its type.
    else{
       mIMG = document.createElement("img");
       mIMG.src = "source";
       x.appendChild(mIMG);
    }
    
    //now the loop
    while( your_condition )
        mIMG.src = "source of the image";
    

    这样,您只使用和编辑一个元素。

    【讨论】:

    • 嘿..你似乎有这个目标..thx 很多..而且我总是更喜欢使用 x.innerHTML..但在这种情况下,因为我面临一些问题..所以我使用createElement的方式,.src ..最后是否仍然可以以某种方式使用x.innerHTML?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多