如何在函数中为每个开关案例添加url图像



如何在函数中为每个开关情况添加url图像?(以便图像显示在myboxdiv中,同时单击按钮上的文本(

function tests() {
let combo = document.getElementById("string_determine");
let div = document.getElementById("mybox");
let string_determine;
switch (combo.options[combo.selectedIndex].text) {
case '"red" + "blue"':
string_determine = "purple";
div.style.color = "purple";
break;
case '"blue" + "green"':
string_determine = "turquoise";
div.style.color = "turquoise";
break;
case '"green" + "red"':
string_determine = " brown";
div.style.color = "brown";
break;
default:
string_determine = "NONE";
}
console.log(string_determine);
document.getElementById("mybox").innerHTML = string_determine;
}
<!doctype html>
<html>
<script src="test.js"></script>
<select name="string_determine" id="string_determine">
<option value=>Select Value</option>
<option value='"red" + "blue"'>"red" + "blue"</option>
<option value='"blue" + "green"'>"blue" + "green"</option>
<option value='"green" + "red"'>"green" + "red"</option>
</select>
<button onclick="tests()">Yes</button>

<!-- this is the box -->
<div class="container">
<h3> Selection </h3>
<div id="mybox" class="box">
<label for="mybox"> </label>
<output name="mybox" type="text"><br>
</div>
</div>
</body>
</html>

下面的代码应该会对您有所帮助。

看看下面的行:

document.getElementById("mybox").innerHTML = 
"<img src='" + IMAGE_SOURCE + string_determine + "'><p>" + string_determine + "</p>";

当运行下面的代码片段时,您应该等待几秒钟,以便从互联网加载图像。

const IMAGE_SOURCE = "https://source.unsplash.com/random/100x100/?";
const IMAGE_EXTENSION = "";
// const IMAGE_SOURCE = "https://example.com/images/";
// const IMAGE_EXTENSION = ".png";
function tests() {
let combo = document.getElementById("string_determine");
let div = document.getElementById("mybox");
let string_determine;
switch (combo.options[combo.selectedIndex].text) {
case '"red" + "blue"':
string_determine = "purple";
div.style.color = "purple";
break;
case '"blue" + "green"':
string_determine = "turquoise";
div.style.color = "turquoise";
break;
case '"green" + "red"':
string_determine = "brown";
div.style.color = "brown";
break;
default:
string_determine = "NONE";
}
let myBoxHTML = `<img src="${IMAGE_SOURCE}${string_determine}${IMAGE_EXTENSION}"><p>${string_determine}</p>`;
console.log(myBoxHTML);
document.getElementById("mybox").innerHTML = myBoxHTML;
}
<select name="string_determine" id="string_determine">
<option value=>Select Value</option>
<option value='"red" + "blue"'>"red" + "blue"</option>
<option value='"blue" + "green"'>"blue" + "green"</option>
<option value='"green" + "red"'>"green" + "red"</option>
</select>
<button onclick="tests()">Yes</button>
<div class="container">
<h3>Selection</h3>
<div id="mybox" class="box">
</div>
</div>
<script src="app.js" async defer></script>

最新更新