Javascript 当变量达到某个值时,如何显示图像?
到目前为止,我已经做到了,当变量poeng的值超过12时,它会显示消息Hello World,但是如果我想让它显示一个图像呢 HTML 五, 七, +5 javascript的编码Javascript 当变量达到某个值时,如何显示图像?,javascript,image,if-statement,Javascript,Image,If Statement,到目前为止,我已经做到了,当变量poeng的值超过12时,它会显示消息Hello World,但是如果我想让它显示一个图像呢 HTML 五, 七, +5 javascript的编码 var poeng = 0; function myFunction() { poeng = 5; console.log(poeng) check() } function myFunction2() { poeng = 7; console.log(poeng) check() } functio
var poeng = 0;
function myFunction() {
poeng = 5;
console.log(poeng)
check()
}
function myFunction2() {
poeng = 7;
console.log(poeng)
check()
}
function myFunction3() {
poeng = poeng + 5;
console.log(poeng)
check()
}
function check() {
if(poeng > 12) {
console.log("Hello World");
//here i want it to display an image
}
}
只需将您的控制台更换为上面列出的任何一款即可。下面是id为image的div的示例:
$('#image').html('<img src="url" />');
要显示图像而不是仅仅输出到控制台,您必须创建一个属性,然后将其附加到页面内的元素 这里有一个例子。图像是使用一个小辅助函数创建的,并附加到check函数内的元素:
var poeng = 0;
var imgURL = 'https://fillmurray.com/1000/645'; // <-- URL of the image, using a placeholder service for now
// --- Image creation helper
function createImage(url) {
var imgEl = document.createElement('img'); // <-- create an <img> node/element
imgEl.alt = ''; // <-- add an alt-attribute
imgEl.src = url; // <-- add it's source
return imgEl; // <-- return the <img> to the caller
}
function myFunction() {
// ... elided for brevity ...
}
function myFunction2() {
// ... elided for brevity ...
}
function myFunction3() {
// ... elided for brevity ...
}
function check() {
if(poeng > 12) {
console.log("Hello World");
//here i want it to display an image
var imgEl = createImage(imgURL); // <-- create the <img>
document.body.appendChild(imgEl); // <-- add it to the <body> element
}
}
取消隐藏HTML元素?是否创建HTML元素并将其附加到页面?有很多方法可以实现这一点。您必须创建Image元素see document.createElemen,设置其属性并将其附加到DOM see ParentNode。append似乎OP需要一个不使用jQuery的解决方案。谢谢David!我对Javascript真的很陌生,所以像你这样的人很好地帮助我处理这样的事情。