2012-12-15 118 views
1

我不知道为什么,但我的Javascript只能在Firefox和IE中运行一次(但它在Chrome中正常运行)。有人知道为什么吗?Javascript只能使用一次?

<script type="text/javascript"> 
function changeDivImage() 
     { 
     var imgPath = new String(); 
     imgPath = document.getElementById("div1").style.backgroundImage; 
     if (imgPath == "url(images/1.jpg)" || imgPath == "") 
      { 
      document.getElementById("div1").style.backgroundImage ="url(images/2.jpg)"; 
      } 
     else if (imgPath == "url(images/2.jpg)") 
      { 
      document.getElementById("div1").style.backgroundImage = "url(images/3.jpg)"; 
      } 
     else if (imgPath == "url(images/3.jpg)") 
      { 
      document.getElementById("div1").style.backgroundImage = "url(images/1.jpg)"; 
      } 
     } 
    </script> 

脚本可以通过点击图像

<img src="images/leftarrow.png" 
    value="Change Background Image" 
    onclick="changeDivImage()" /> 
+2

检查什么imgPath'的'值一次变化的背景之后。 –

+0

您是否收到任何错误?你是否已经开始使用调试器来查看条件是否按照预期进行评估? –

+1

'new String()'?真?你意识到你立即通过给同一个变量分配一个值来抛弃这个对象,对吗? –

回答

1

浏览器往往会以不同的方式来标准化CSS属性触发。例如,IE和Firefox在URL上加上引号。

那么,也许你应该改为尝试这个办法:

var div = document.getElementById('div1'), 
    imgPath = parseInt(div.style.backgroundImage.match(/\d(?=\.jpg)/) || ["0"],10), 
    newnum = imgPath%3+1; 
div.style.backgroundImage = "url(images/"+newnum+".jpg)"; 
+0

或者开始使用jQuery并使用'.attr(“src”)'..和瞧! – Tom

+0

@Tom:......认真?如果这是一个严肃的答案,那么我恨你。 –

+0

不是那么认真的回答,不是..但是你真的很鄙视jQuery以至于你恨我吗?你真的有什么反对呢? – Tom