簡體   English   中英

將多個輸入值傳遞給函數以更新圖像

[英]Pass multiple input values to a function to update an image

我想根據輸入的兩個輸入值更改圖像。 這將如何通過兩個單獨的輸入動態完成? 到目前為止,這是我的代碼。

 function twoinputs() { var size1 = document.getElementById("size1").value; var size2 = document.getElementById("size2").value; var getValue = size1.value; var getValue2 = size2.value; if (getValue == "1" && getValue2 == "1") { document.getElementById('optimus').style.backgroundImage = "url('http://www.orderofinterbeing.org/wp-content/uploads/2014/04/light-forest.jpg')"; } else if (getValue == "2" && getValue2 == "2") { document.getElementById('optimus').style.backgroundImage = "url('http://freebigpictures.com/wp-content/uploads/2009/09/coniferous-forest.jpg')"; } } twoselects();
 p { width: 100%; height: 200px; }
 <img class="prime" src="images/image_small.jpg"> <form> Select image size: <input id='size1' name='size1' onchange="twoinputs()"> <input id='size2' name='size2' onchange="twoinputs()"> </form> <p id="optimus"></p>

首先,輸入是自關閉的,因此將 HTML 更改為

<img class="prime" src="https://pbs.twimg.com/profile_images/604644048/sign051.gif">
<form>
    Select image size:
    <input id='size1' name='size1'>
    <input id='size2' name='size2'>
</form>
<p id="optimus"></p>

在腳本中,問題在於您獲得了兩次值,並且您混淆了函數名和一些變量。

您還可以使用適當的事件處理程序

var elem1 = document.getElementById("size1");
var elem2 = document.getElementById("size2");
var image = document.getElementById('optimus');

function twoinputs() {
    var size1 = +elem1.value;
    var size2 = +elem2.value;

    if (size1 === 1 && size2 === 1) {
        image.style.backgroundImage = "url('http://www.orderofinterbeing.org/wp-content/uploads/2014/04/light-forest.jpg')";
    } else if (size1 == 2 && size2 == 2) {
        image.style.backgroundImage = "url('http://freebigpictures.com/wp-content/uploads/2009/09/coniferous-forest.jpg')";
    }
}

twoinputs();

elem1.addEventListener('change', twoinputs, false);
elem2.addEventListener('change', twoinputs, false);

小提琴

看起來不錯,但你有 .value 兩次所以 size1.value 不會有屬性值,換句話說:

function twoinputs() {
var size1 = document.getElementById("size1");
var size2 = document.getElementById("size2");
var getValue = size1.value;
var getValue2 = size2.value;**
if (getValue == "1" && getValue2 == "1") {
document.getElementById('optimus').style.backgroundImage = "url('http://www.orderofinterbeing.org/wp-content/uploads/2014/04/light-forest.jpg')";
} else if (getValue == "2" && getValue2 == "2") {
document.getElementById('optimus').style.backgroundImage = "url('http://freebigpictures.com/wp-content/uploads/2009/09/coniferous-forest.jpg')";
}
}
twoselects();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM