2013-04-11 127 views
0

好吧,那确实是一个很奇怪的问题,但它真的发生在我身上,我写了一个JS,它在IE上工作,但它没有火狐或铬。在IE上工作的JS,不能在Chrome和FF上工作

我希望如果有人能与为什么发生这种情况赐教...

我的HTML代码是下一个

<h4>What kind of animals do you like the most?</h4> 
<select id="animalName" name="animalName"> 
    <option selected="selected" disabled="disabled">Which animal is it?</option> 
    <option value="Cat">Cat</option> 
    <option value="Dog">Dog</option> 
    <option value="Lion">Lion</option> 
    <option value="Other">Other</option> 
</select> 
<div id="otherAnimalNameDiv"> 
    <h4>As you picked the other, would you like to write it down to let us know?</h4> 
    <input type="text" name="otherAnimalName" size="40" id="otherAnimalName" /> 
</div> 

而我的JS代码是下一个:

var animalName = document.getElementById("animalName"); 
    var animalOtherName = document.getElementById("otherAnimalNameDiv"); 

    function animalSelect(){ 
     animalName.onchange = function(){ 
      if (animalName.options.value == "Other"){ 
       animalOtherName.style.display = "block"; 
      } 
     }; 
     animalOtherName.style.display = "none"; 
    } 

window.onload = function() { 
    firstNameFunc(); 
    familyNameFunc(); 
    emailAddressFunc(); 
    passwordFunc(); 
    rewritePasswordFunc(); 
    colorPickerFunc(); 
    animalSelect(); 
    } 

为什么它会在IE上运行,而不会在Chrome或FF上运行?...

当您选择“其他”选项时从选择标签它应该设置div显示屏蔽,这发生在IE上,但不是FF或铬。

+1

你有没有真的_invoke_' animalSelect'? – Zeta 2013-04-11 18:44:35

+0

你没有真正解释过什么对你的代码不起作用。另外,一些JS代码可能在一个浏览器中工作,但不是另一个,这并不奇怪。它被称为[跨浏览器兼容性](https://www.google.com/search?q=cross+browser+compatibility)。 – Travesty3 2013-04-11 18:46:56

回答

2

我愿意打赌,问题是你的if语句:

if (animalName.options.value == "Other"){ 

如果你正在试图获得所选选项的值,你应该尝试更类似的东西:

if (animalName.options[animalName.selectedIndex].value == "Other"){ 
+0

对不起,比你快8秒;)无论如何都要+1。 – 2013-04-11 18:52:29

+0

真棒,它现在的作品!谢谢! 你介意解释发生了什么? @ _ @ – 2013-04-11 18:56:55

+0

OKes,我现在明白了,想通了;) – 2013-04-11 19:02:21

0

您尝试获取选项值是错误的。它应该是:

if(this.options[this.selectedIndex].value == "Other") { 
+0

他只是在问题中加了这个,但是用他调用函数的方式(而不是事件监听器),你将无法使用'this'。 – Travesty3 2013-04-11 18:54:26

+0

非常感谢:D – 2013-04-11 18:58:41

相关问题