javascript - 通过 javascript 的 IE/Firefox 风格更新不起作用

标签 javascript html dynamic internet-explorer-8 styles

我有一个程序,它从自动完成中获取名称并将其发送到一个 JavaScript 函数,该函数动态创建一个带有按钮的标签。当我尝试使用 DOM 方法设置样式属性时,它在 Firefox/IE 7 中不起作用,但在 IE 8/Chrome 中起作用。 这是函数,

function fnCreate(client) {
                    var newLbl = document.createElement("label");
                    var newBtn = document.createElement("input");
                    var hidden = document.getElementById("count");
                    var val = parseInt(hidden.value) + 1;
                    hidden.setAttribute("value", val);
                    newLbl.setAttribute("id", "lbl" + client + val);
                    newBtn.setAttribute("id", "btn" + client + val);
                    newBtn.setAttribute("type", "button");
                    newBtn.setAttribute("style", "background-color: #6D84B4; background-image: url('X.png'); vertical-align: middle; background-repeat: no-repeat; text-align: center; height: 14px;border-style: none;  border-width: 0px; ");
                    newLbl.innerHTML = client;
                    newLbl.setAttribute("style", "background-color: #6084B4; color: #FFFFFF");
                    newBtn.setAttribute("onclick", "fnDelete('" + client + val + "')");
                    newLbl.appendChild(newBtn);
                    myData.appendChild(newLbl);

输入参数“client”是名称。它应该将按钮附加到标签,然后将标签附加到 myData,它是表内的 div。

<label id="lblDimitris1" style="">

这是页面加载后 IE8 的标记

最佳答案

我认为最好的解决方案是实际创建 2 个类,这将提高可维护性。你的 css 类看起来像这样

.button1 {
    background-color: #6D84B4; 
    background-image: url('X.png'); 
    vertical-align: middle; 
    background-repeat: no-repeat; 
    text-align: center; 
    height: 14px;
    border: 0; 
}

.label1 {
    background-color: #6084B4; 
    color: #FFFFFF;
 }

在你的 JavaScript 中你现在可以做这样的事情

newBtn.className = 'button1';
newLbl.className = 'label1';

更容易阅读和维护。

完整代码如下

function fnCreate(client) {
    var newLbl = document.createElement('label');
    var newBtn = document.createElement('input');
    var hidden = document.getElementById('count');

    var val = parseInt(hidden.value) + 1;

    hidden.value = val;
    newLbl.id = 'lbl' + client + val;
    newBtn.id = 'btn' + client + val;
    newBtn.type = 'button';
    newBtn.className = 'button1';
    newBtn.onclick = fnDelete(client + val);
    newLbl.innerHTML = client;
    newLbl.className = 'label1'

   newLbl.appendChild(newBtn);
   myData.appendChild(newLbl);
}

关于javascript - 通过 javascript 的 IE/Firefox 风格更新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6681512/

相关文章:

javascript - 在 angularjs 服务中缓存数组

internet-explorer - audio.currentTime 在 IE9 中不起作用

javascript - 向span标签添加href

c++ - 掷硬币游戏 : Optimization problem

c++ - 在 C++ 中创建动态数据类型

javascript - CKEditor初始高度

javascript - Dialog Widget-如何弹出点击图片?

javascript - 用 PHP 加载 CSS(可能还有 JS)

javascript - 如何使用 JavaScript 获取链接标题

asp.net - 如何动态编译ashx文件?