将您的代码更改为此,以正确声明本地变量fs
一次。然后,您可以可靠地在代码的末尾测试以确定它是否已设置。以前的代码可能会因变量提升而起作用,但它不是推荐的编码方式。一个变量的作用域是它在声明的功能。
function toggleDeliveryOption(source) {
var fs = null;
if(source.toLowerCase() === "maildeliveryoption")
{
fs = document.getElementById("mailDeliveryOptionFS");
}
else if(source.toLowerCase() === "faxdeliveryoption")
{
fs = document.getElementById("faxdeliveryoptionFS");
}
else if(source.toLowerCase() === "emaildeliveryoption")
{
fs = document.getElementById("emaildeliveryoptionFS");
}
if (fs)
{
if (fs.style.display == "none") {
fs.style.display = "block";
} else {
fs.style.display = "none";
}
}
}
的其他潜在这里小问题,就是fs.style.display
可能不会被预先设置为阅读风格变量这种方式只返回明确的内嵌样式的HTML(它不返回事情通过CSS设置)。如果您想知道显示设置的实际状态,则必须使用包含CSS设置的计算样式。在windows中获得计算样式是不同的,因此需要多行代码才能完成。这是我使用像YUI或jQuery这样的框架的原因之一,因为它为我处理所有这些跨浏览器混乱。
顺便说一句,你可以简化代码像这样的很多:
function toggleDeliveryOption(source) {
var fs = document.getElementById(source);
if (fs) {
if (fs.style.display == "none") {
fs.style.display = "block";
} else {
fs.style.display = "none";
}
}
}
为了使这个简单的版本的工作,只是通过期权的ID切换:
toggleDeliveryOption("mailDeliveryOptionFS");
如果你想实际的显示状态包括CSS设置,那么你需要使用这个:
// add IE compatibility function for getComputedStyle
if (!window.getComputedStyle) {
window.getComputedStyle = function(el, pseudo) {
this.el = el;
this.getPropertyValue = function(prop) {
var re = /(\-([a-z]){1})/g;
if (prop == 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function() {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
function toggleDeliveryOption(source) {
var fs = document.getElementById(source);
if (fs) {
var style = getComputedStyle(fs, null);
if (style.display == "none") {
fs.style.display = "block";
} else {
fs.style.display = "none";
}
}
}
这应该不是问题...源代码如何设置? –
@Joseph源是基于点击事件复选框 邮件 –
你可以显示HTML,因为它将需要?我相信你可能在JavaScript代码中拼错了你的ID。 ID区分大小写。 'mailDeliveryOptionFS'在其他两个不是的情况下是骆驼式的。 –