如何使用select标签和javascript更改div的背景?

时间:2016-03-30 02:56:00

标签: javascript jquery

我在这里找到了我的问题的答案,但它对我来说真的不起作用。我是编程新手,还不熟悉使用javascript。可悲的是,我'一直在试图相当长一段时间做到这一点。

我想要做的是每当我更改select标签中的选项时更改div的背景。这是我的.JSP代码

Add Ons Type:
<select id="addOnsType" name="addOnsType" onchange="changePicture()">
    <option selected disabled> select add ons</option>
    <c:forEach var="addOnsType" items="${addOnsType}">
        <option value="${addOnsType.addOnsTypeId}"> ${addOnsType.description} </option>
    </c:forEach>
</select>

<div id="PictureDiv" style="height: 58px; width: 344px">
</div>

addOnsTypeId的值为1,2和3。

虽然我的javascript被写成(我已经使用了我在这里看到的)

function changePicture() {

    var PictureDivBG = document.getElementById("PictureDiv");
    var addOnsTypeSelected = document.getElementById("addOnsType");

    if (addOnsTypeSelected.val() == 1) {
        PictureDivBG.style.backgroundImage = "url('../images/cartoon1.jpg')";
    } else if (addOnsTypeSelected.val() == 2) {
        PictureDivBG.style.backgroundImage = "url('../images/cartoon2.jpg')";
    } else if (addOnsTypeSelected.val() == 3) {
        PictureDivBG.style.backgroundImage = "url('../images/cartoon3.jpg')";
    }

};    

非常感谢任何帮助/提示/答案。谢谢!

跟进新手问题:我对javascript和jQuery很困惑,有什么区别?

1 个答案:

答案 0 :(得分:1)

addOnsTypeSelected是dom元素引用,它没有jQuery提供的val()函数。

您可以使用id选择器获取这些元素的jQuery对象并获取值

function changePicture() {
  var addOnsTypeSelected = $("#addOnsType").val(),
    backgroundImage;

  if (addOnsTypeSelected == 1) {
    backgroundImage = "url('../images/cartoon1.jpg')";
  } else if (addOnsTypeSelected == 2) {
    backgroundImage = "url('../images/cartoon2.jpg')";
  } else if (addOnsTypeSelected == 3) {
    backgroundImage = "url('../images/cartoon3.jpg')";
  }
  $('#PictureDiv').css('background-image', backgroundImage);

};

但是使用jQuery事件处理程序,你可以

jQuery(function() {
  var imgs = {
    1: 'url(//placehold.it/64/ff0000)',
    2: 'url(//placehold.it/64/00ff00)',
    3: 'url(//placehold.it/64/0000ff)'
  }
  $('#addOnsType').change(function() {
    $('#PictureDiv').css('background-image', imgs[$(this).val()] || 'none');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add Ons Type:
<select id="addOnsType" name="addOnsType">
  <option selected disabled>select add ons</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<div id="PictureDiv" style="height: 58px; width: 344px">
</div>