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

时间:2016-04-06 09:56:33

标签: javascript html function input onchange

我想根据输入的两个输入值来更改图像。如何通过两个独立的输入动态完成?到目前为止,这是我的代码。



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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

首先,输入是自动关闭的,因此将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

答案 1 :(得分:0)

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