【问题标题】:Create HTML element dynamically?动态创建 HTML 元素?
【发布时间】:2015-01-19 15:19:23
【问题描述】:

我在 javascript 方面比较新,所以也许我的问题对你们中的一些人来说似乎很重要。 我有这一行是创建 div 元素:

 <div id = "popUpWin" style = "width:' + width + 'px; height:' + height + 'px;"></div>;

我的问题是如何使用 JavaScript 动态创建这一行?

【问题讨论】:

标签: javascript


【解决方案1】:

至少有几种方法可以做到这一点。

  1. 使用document.createElement,这是DOM API 函数之一。

    // Create the element
    var d = document.createElement('div');
    
    // Set its ID
    d.id = "popUpWin";
    
    // Set the style properties on the element's `style` object
    d.style.width = width + "px";
    

    d.style.height = 高度 + "px";

    ...然后大概使用appendChildinsertBefore 或在文档中已有的另一个元素上的类似元素将其放在文档中的某个位置。

  2. 在现有元素上使用insertAdjacentHTML

    theOtherElement.insertAdjacentHTML(
        'beforeend',
        '<div id = "popUpWin" style = "width:' + width + 'px; height:' + height + 'px;"></div>'
    );
    

    该示例会将div 作为子元素添加到现有元素的末尾(不会干扰其中已有的其他元素)。

  3. 在现有元素上使用innerHTML,如果您想替换其内容:

    theOtherElement.innerHTML =
        '<div id = "popUpWin" style = "width:' + width + 'px; height:' + height + 'px;"></div>';
    

    请注意,这将删除 theOtherElement 中的任何其他元素,并将它们替换为 div

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 2011-07-29
    • 2015-11-05
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多