2015-10-26 27 views
0

工作這個變量表示一個輸入其中類型=文本的setAttribute未在IE

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時,我得到這個錯誤消息。

My error message

我試圖使用屬性符號

element.disabled=true; 

,但似乎並沒有工作,因爲如果通過屬性設置標記它不會立即更新或東西。我會發佈一個小提琴,但這是行不通的,因爲這個bug只發生在IE中,所以JSFiddle不會複製它。

有什麼方法可以糾正這個問題嗎?一個polyfill可能?請不要Jquery。

+0

此功能範圍。在超時之外嘗試'var that = this',並在裏面使用'that'。 – Oriol

+0

我會試一試。謝謝。 – Leshy

回答

1


這裏的問題是在其他方面setTimeout運行,然後在關鍵字this沒有引用到x,這意味着沒有DOM元素,但全球對象(window)。

而不是使用this關鍵字,使用變量x引用您的DOM元素,例如:

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(); 
1

thissetTimeout處理程序指的是window而不是<div id="fiber-count">。您需要存儲this並在setTimeout內使用它。

var self = this; 
setTimeout(function(){self.setAttribute('placeholder','');},3000); 

或者,

setTimeout(function(){this.setAttribute('placeholder','');}.bind(this),3000); 
0

道歉虛驚一場。我發現了這個問題:我有另一個名爲x的變量,由於另一個變量x是一個局部變量,所以onchange函數中的X引用指向另一個全局變量x。我只是簡單地將局部變量x改爲一個全局變量k,以及所有對它的引用。這解決了問題。