将多个输入值传递给函数以更新图像

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);

FIDDLE

看起来不错,但是你有两次 .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();