我正在尝试根据JS应用的结果显示不同的图像。
我的HTML + JS现在看起来如下。
if (c == 2) {
document.getElementById('result').innerHTML = num + ' is a Prime number';
var imageshown = "OptimusPrime.gif"
}else{
document.getElementById('result').innerHTML = num + ' is NOT a Prime number';
var imageshown = "Megatron.gif"
}
}
</script>
<div class="container">
<form id="contact" method="post">
<h3>Prime-O-Tron</h3>
<h4>Please fill in a number in the field below and press "Calculate" to see if it is a prime number or not.</h4>
Please enter a number:
<input type="number" id="num" name="num" min="0" />
<input type="button" value="Find Prime Number" onclick="findPrime()" name="find" />
<div style="margin-top: 10px;" id="result"></div>
<img src= imageshown>
但是无论结果是来自if还是else,它都不会显示任何图像。
如何根据JS的结果嵌入其他图像?
答案 0 :(得分:1)
您可以更改src
而不是更新变量的值。您也可以这样简化:
if (c == 2) {
msg = num + ' is a Prime number';
imageshown = "OptimusPrime.gif"
} else {
msg = num + ' is NOT a Prime number';
imageshown = "Megatron.gif"
}
var result = document.getElementById('result');
var img = result.nextElementSibling;
result.textContent = msg;
img.src = imageshown;
} // <--function closing
答案 1 :(得分:-1)
尝试一下
html
<img id='img' src= imageshown>
javascript
if (c == 2) {
document.getElementById('result').innerHTML = num + ' is a Prime number';
var imageshown = "OptimusPrime.gif"
} else {
document.getElementById('result').innerHTML = num + ' is NOT a Prime number';
var imageshown = "Megatron.gif"
}
document.getElementById('img').src = imageshown;