如何显示基于变量的条件图像



我正试图根据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的结果嵌入不同的图像?

您可以更改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

试试这个,

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;

最新更新