我在HTML中创建一个选择菜单,当您在列表中更改选择时,它会更改图像的src。我一直收到错误:"无法设置属性' src' of null"在控制台中,图像不会出现。这是代码:
var panelOneType;
function gfsPanelOne() {
panelOneType = "gfs";
}
function cmcPanelOne() {
panelOneType = "cmc";
}
function navgemPanelOne() {
panelOneType = "navgem";
}
function nam12kmPanelOne() {
panelOneType = "nam12km";
}
function nam4kmPanelOne() {
panelOneType = "nam4km";
}
function wrfarwPanelOne() {
panelOneType = "wrf-arw";
}
function wrfnmmPanelOne() {
panelOneType = "wrf-nmm";
}
function rgemPanelOne() {
panelOneType = "rgem";
}
document.getElementById("panel1").src = "http://www.tropicaltidbits.com/analysis/models/" + panelOneType + "/2016062712/" + panelOneType + "_mslp_pcpn_frzn_us_1.png";

<select name="panel-1" class="model-select">
<option value="gfs" onchange="gfsPanel1()">GFS</option>
<option value="cmc" onchange="cmcPanel1()">CMC</option>
<option value="navgem" onchange="navgemPanel1()">NAVGEM</option>
<option value="nam-12km" onchange="nam12kmPanel1()">NAM 12km</option>
<option value="nam-4km" onchange="nam4kmPanel1()">NAM 4km</option>
<option value="wrf-arw" onchange="wrfarwPanel1()">WRF-ARW</option>
<option value="wrf-nmm" onchange="wrfnmmPanel1()">WRF-NMM</option>
<option value="rgem" onchange="rgemPanel1()">RGEM</option>
</select>
<img class="model-image" id="panel1" src="" />
&#13;
任何人都知道我为什么会收到此错误以及如何解决此问题?
答案 0 :(得分:1)
您需要定义一个函数并在select&#34; onchange&#34;
上调用它试试这个:
function changeImage(){
var panelOneType = document.getElementById('selectedvalue').value;
console.info(panelOneType);
document.getElementById("panel1").src = "http://www.tropicaltidbits.com/analysis/models/" + panelOneType + "/2016062712/" + panelOneType + "_mslp_pcpn_frzn_us_1.png";
}
&#13;
<select name="panel-1" id="selectedvalue" class="model-select" onchange="changeImage();">
<option value="gfs" >GFS</option>
<option value="cmc" >CMC</option>
<option value="navgem" >NAVGEM</option>
<option value="nam-12km" >NAM 12km</option>
<option value="nam-4km" >NAM 4km</option>
<option value="wrf-arw" >WRF-ARW</option>
<option value="wrf-nmm" >WRF-NMM</option>
<option value="rgem" >RGEM</option>
</select>
<img class="model-image" id="panel1" src="" />
&#13;
答案 1 :(得分:0)
正如Rhumborl对您的问题发表评论时,最有可能的情况是您正在加载javascript而不考虑html是否已经呈现,如果您使用jquery或文档,如果您在文档就绪状态下触发它肯定会有效.readyState =='完成'或者你可以这样做:
document.addEventListener("DOMContentLoaded", function(event) {
//Do work
});