讓我們來想象我有這樣的代碼:的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">
它會導致什麼。警報未出現,並且input
的src
未交換到其他圖像。爲什麼?
編輯:如果我使用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:它現在神奇地工作。但我不知道發生了什麼。
那麼必須有一個bug呢。我想:'不能訪問未定義的屬性src。腳本塊在你的頁面中的哪個位置?爲此,腳本塊需要位於'img'之後。 – Mouser 2015-02-11 17:44:31
是的。它在頁面結束之前。 – 2015-02-11 17:50:57
然後我根據Avitus選項。 – Mouser 2015-02-11 17:51:48