2015-02-11 26 views
0

讓我們來想象我有這樣的代碼:的Javascript:試圖改變輸入SRC在一個特定的屏幕寬度

<script> 
     if (screen.width > 1008) { 
      alert("A"); 
     } 
     else{ 
      alert("B"); 
     } 
</script> 

它實際上打印一個,如果我在超過1008px寬的屏幕加載它。但是,如果我這樣做:

<script> 
      if (screen.width > 1008) { 
       document.querySelector('#inputDicionario').src = "other_image.png"; 
       alert("A"); 
      } 
      else{ 
       alert("B"); 
      } 
    </script> 

這樣inputDicionario是指以下輸入:

<input class="botaoDicionario" type="image" src="icone_dicionario.jpg" value="" id="inputDicionario"> 

它會導致什麼。警報未出現,並且inputsrc未交換到其他圖像。爲什麼?

編輯:如果我使用inputDicionario s類代替它的ID,它的工作原理。

編輯2:在控制檯,將出現以下錯誤:

CLAWS.html:10 Uncaught TypeError: Cannot set property 'src' of null 
CLAWS.html:87 Uncaught TypeError: undefined is not a function 

在線10中,輸入被定義。在第87行,有腳本。

編輯3:它現在神奇地工作。但我不知道發生了什麼。

+0

那麼必須有一個bug呢。我想:'不能訪問未定義的屬性src。腳本塊在你的頁面中的哪個位置?爲此,腳本塊需要位於'img'之後。 – Mouser 2015-02-11 17:44:31

+0

是的。它在頁面結束之前。 – 2015-02-11 17:50:57

+0

然後我根據Avitus選項。 – Mouser 2015-02-11 17:51:48

回答

0

沒有什麼可能發生的原因是查詢選擇器只適用於更現代的類型的瀏覽器。 你可以看到支持的瀏覽器:http://www.w3schools.com/jsref/met_document_queryselector.asp

我建議你改變你的腳本是:

<script> 
      if (screen.width > 1008) { 
       document.getElementById('inputDicionario').src = "other_image.png"; 
       alert("A"); 
      } 
      else{ 
       alert("B"); 
      } 
    </script> 
+0

沒有幫助:/ – 2015-02-11 17:52:55