如何在创建选项时更改其背景图像

How can I change the background-image of an option while creating it?

本文关键字:背景 图像 创建 选项      更新时间:2023-09-26

我正在select元素中创建一个选项,并试图更改背景图像。

nextItem = document.createElement('option');
nextItem.innerHTML = text;
nextItem.style.backgroundImage = "url(icons/add.png);";
nextItem.className = "class1";

然而,当我使用firebug时,我可以看到实际创建的是:

<option class="class1" style="">text</option>

为什么它创建了样式属性,却没有在其中放入任何信息?

删除url中的分号。

更改:

nextItem.style.backgroundImage = "url(icons/add.png);";

至:

nextItem.style.backgroundImage = "url(icons/add.png)";

jsFiddle示例

您可以尝试此nextItem.style.backgroundImage = "url('icons/add.png')";