我有一个程序,它从自动完成中获取一个名称,并将其发送给一个javascript函数,该函数动态地创建一个Label,其中包含一个按钮。当我尝试使用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上,myData是表中的一个div。
<label id="lblDimitris1" style="">
这是IE8页面加载
我认为最好的解决方案是创建两个类,这将提高可维护性。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);
}
试试这个:
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.style.value = val;
newLbl.style.id = 'lbl' + client + val;
newBtn.style.id = 'btn' + client + val;
newBtn.type = 'button';
newBtn.style.backgroundColor = '#6D84B4';
newBtn.style.backgroundImage = 'url(X.png)';
newBtn.style.backgroundRepeat = 'no-repeat';
newBtn.style.verticalAlign = 'middle';
newBtn.style.textAlign = 'center';
newBtn.style.height = '14px';
newBtn.style.border: '0px';
newBtn.onclick = fnDelete(client + val);
newLbl.innerHTML = client;
newLbl.style.backgroundColor = '#6084Bd';
newLbl.style.color = '#FFFFFF';
newLbl.appendChild(newBtn);
myData.appendChild(newLbl);
}
setAttribute不兼容跨浏览器。有些事我不是百分百确定。如果您的客户机或val变量被类型转换为数字,则onclick fnDelete()函数中的参数连接应该可以工作,但这取决于您。也不确定是否可以这样设置元素的类型,但如果上面的代码在某些浏览器上工作,也应该这样。