此变量表示 type=text 的输入
var x=document.getElementById('fiber-count');
我有这个功能:
x.onkeyup=function(){
var u=x.value;
var v=parseInt(u);
var n=isNaN(u);
if(n){
this.setAttribute('placeholder', 'Invalid Character');
setTimeout(function(){this.setAttribute('placeholder','');},3000);
x.value="";
}
if(v<1){
this.setAttribute('placeholder', "Min. value is 1");
setTimeout(function(){this.setAttribute('placeholder','');},3000);
x.value='';
}
if(v>864){
this.setAttribute('placeholder', 'Max. value is 864');
setTimeout(function(){this.setAttribute('placeholder','');},3000);
x.value='';
};
if(v<=12&&v>=1){
tr.removeAttribute('disabled');
}else{
tr.setAttribute('disabled', 'disabled');
}
if(v==2){
swr.removeAttribute('disabled');
}else{
swr.setAttribute('disabled', 'disabled');
}
if(v!==2){
document.getElementById('cable_type').selectedIndex='0';
f_c.classList.remove('hidden');
var top=document.getElementsByName('subunit');
for(i=0; i<top.length; i++){
top[i].removeAttribute('disabled');
}
}
if(v==1){
document.getElementById('radio_option_1').checked=true;
}
if(v==12&&bast[0].checked){
document.getElementById('diameter').selectedIndex='3';
}
if(v>=12||v==8){
document.getElementById('sub_four').removeAttribute('disabled');
console.log('ribbon ought to be enabled');
}else{
//document.getElementById('sub_four').setAttribute('disabled', 'disabled');
document.getElementById('sub_four').setAttribute('disabled', 'disabled');
console.log('ribbon disabled')
}
};
问题是:所有 setAttribute() 方法都无法在 IE 中工作。我不明白为什么。我正在使用 setAttribute() 方法来设置多个元素的占位符和禁用属性。问题是这样的:当我在输入中键入 12 时,我收到此错误消息。
我尝试使用属性符号
element.disabled=true;
但这似乎不起作用,好像通过属性符号设置它不会立即更新它或其他东西。我会发布一个 fiddle ,但这不起作用,因为这个错误只发生在 IE 中,所以 JSFiddle 不会复制它。
有什么办法可以纠正这个问题吗?也许是聚填充物?请不要使用 Jquery。
最佳答案
这里的问题是 setTimeout
在其他上下文中运行,那么关键字 this
没有引用 x
,这意味着不是 DOM 元素,而是全局对象(窗口
)。
使用变量 x
来引用您的 DOM 元素,而不是使用 this
关键字,例如:
x.setAttribute
而不是 this.setAttribute
在这里您可以使用此模型进行测试:
var x = {
onkeyup: function() {
console.log("this = x:", this === x);
console.log("this.value:", this.value); //x.value = "hello"
setTimeout(function() {
console.log("-setTimeout-");
console.log("this:", this); //window, not 'x' as expected
console.log("this.value:", this.value); //undefined
}, 3000);
},
value: 'hello'
};
console.log(x.value);
x.onkeyup();
关于javascript - SetAttribute 在 IE 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336737/