2012-07-31 80 views
13

我正在使用JavaScript来禁用按钮。工作正常IE但不是在Firefox和Chrome,这里是我工作的脚本:document.getElementById('btnid')。disabled在firefox和chrome中不工作

function disbtn(e) { 
    if (someCondition == true) { 
     document.getElementById('btn1').disabled = true; 
    } else { 
     document.getElementById('btn1').disabled = false; 
    } 

而且在我的HTML我有:

<input type="button" id="btn1" value="submit" /> 
+0

没有错。它以什么方式不起作用? – Utkanos 2012-07-31 10:00:41

+0

按钮禁用和启用在IE中正常工作。但是Firefox和Chrome没有任何事情发生。在这两个浏览器中,按钮没有任何功能,只能启用。 – steeve 2012-07-31 10:07:13

+0

@Spencer:使用'setAttribute()'和'removeAttribute()'作为我在下面的答案中给出的。 – 2012-07-31 10:09:07

回答

33

使用setAttribute()removeAttribute()

function disbtn(e) { 
    if (someCondition == true) { 
     document.getElementById('btn1').setAttribute("disabled","disabled"); 
    } else { 
     document.getElementById('btn1').removeAttribute("disabled"); 
    } 
} 

SEE DEMO

+0

@AK:你的小提琴在ff和chrome中工作正常,但在我的页面中,同样的问题是渲染...我现在很无能:( – steeve 2012-07-31 10:27:14

+0

你能分享完整的代码吗? – 2012-07-31 10:29:42

+0

@AK:嗯......这是现在工作的很好,我已经重新命名了函数名,它现在正在工作,看起来很有意思...(我的旧函数名是getSelection,我不知道这个名字有什么不对),非常感谢A K ... :) – steeve 2012-07-31 11:32:59

0

总有一些与浏览器奇怪的问题支持的getElementById的,请尝试使用替代以下:

// document.getElementsBySelector are part of the prototype.js library available at http://api.prototypejs.org/dom/Element/prototype/getElementsBySelector/ 

function disbtn(e) { 
    if (someCondition == true) { 
     document.getElementsBySelector("#btn1")[0].setAttribute("disabled", "disabled"); 
    } else { 
     document.getElementsBySelector("#btn1")[0].removeAttribute("disabled"); 
    }  
} 

另外,拥抱的jQuery,你可以简单地这样做:

function disbtn(e) { 
    if (someCondition == true) { 
     $("#btn1").attr("disabled", "disabled"); 
    } else { 
     $("#btn1").removeAttr("disabled"); 
    }  
} 
+1

“浏览器支持getElementById总是存在奇怪的问题” - 雅?世界卫生大会?这是该规范中最一贯实施的部分之一! ...不像我的浏览器不知道的getElementsBySelector。 – Quentin 2012-07-31 10:06:08

+0

如果这个jQuery代码实际上起作用,那么我对图书馆的不喜欢已经上涨了。这两个属性都是无效值,但错误恢复应该将设置为“false”的disabled属性设置为“disabled”。 – Quentin 2012-07-31 10:07:13

+0

@Quentin你是绝对正确的,我的代码是不正确的(没有预先想到打喷嚏的结果)我做了更正。 – 2012-07-31 10:32:49

3

尝试设置disabled直接属性:

if (someCondition == true) { 
    document.getElementById('btn1').setAttribute('disabled', 'disabled'); 
} else { 
    document.getElementById('btn1').removeAttribute('disabled'); 
} 
0

有的时候一些JavaScript功能不适用于某些特定的浏览器。我建议你开始使用JQuery,它给你归JS,照顾不同的浏览器要求

$('#btn1').each(function(){ 
    this.disabled = false; 
}); 
-1

忠于原生(布尔)属性的支持和其强大的语法,如:

[ELEM ] .disabled =条件?真假; //完成!

为了我们自己良好的集体编码体验,请坚持让其他人支持它。

0

另一种选择:在FF和IE

document.formname.elementname.disabled=true 

工作! :)

-1

我试过所有的可能性。除了以下内容,没有任何工作可以帮我 var element = document.querySelectorAll(“input [id = btn1]”); element [0] .setAttribute(“disabled”,true);

相关问题