0

我正在尝试创建一个网站,该网站有一个下拉菜单,允许用户选择一个项目,一个带有标题的图像将出现。我似乎无法弄清楚如何让这个工作。我有一个空白段落标签,将图像附加到文档中。

<!DOCTYPE HTML>
<html>
<head>
    <title>A JavaScript Template Page</title>
    <meta http-equiv="Content-Type" content="text/HTML; charset=utf-8">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/style.css">
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
    <p>
        What kind of mood are you in today?
    </p>
    <select name="menu" id="menu"> //dropdown menu
        <option value="1">
            Choose your option
        </option>
        <option value="2">
            Happy
        </option>
        <option value="3">
            Angry
        </option>
        <option>
            Sad
        </option>
        <option>
            Grumpy
        </option>
    </select>
    <p id="img-swap">

    </p>
    <h1 id="captions"></h1>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

script.js

var img = ['empty', 'happy', 'angry', 'sad', 'grumpy'];
var im = [];
var sayings = ['How are you feeling today?', 'Happy cat is happy', 'Angry cat is angry', 'Sad cat is sad', 'Grumpy cat is grumpy'];

function imgSwap() {
    var checkIndex = $('#selector').prop('selectedIndex');
    if (index === 0) {
        $('#img-swap').hide();
    } else {
        $('#img-swap').html('<img src="images/' + img[index] + '.jpg" width="600px" height="400px" alt="cats">').hide().show();
        }
        $('#captions').html(sayings[index]);
    }
    $(function() {
    for (var i = 1; i < img.length; i++) {
        im[i] = new Image();
        im[i].src='images/' + img[i] +'.jpg'
        }
        $('#selector').change(function() {
        swap_pictures();
    });
});
4

2 回答 2

2

您的代码中有一些非常明显的错误。以下是我在第一次查看您的代码时可以找到的一些基本内容:

  1. 您的 jQuery 是#selector在代码中不存在具有该 ID 的任何内容时定义的。它应该是:

    <select name="menu" id="selector">
    
  2. 在您的.change()方法中,您正在调用swap_pictures()函数,而您已将函数定义为imgSwap().

  3. imgSwap函数中,您正在设置checkIndex变量的值,但稍后在 if 条件中;你有

    if (index === 0) {
    

    whereindex又是未定义的变量。


编辑

我想这几乎就是全部了。修复它们都导致了这个工作小提琴

于 2013-03-13T03:10:27.213 回答
2

您需要使用 jQuery 的函数来运行该change()函数。

这是一个为您精简和工作的 JSFiddle:http: //jsfiddle.net/UckER/ - 我只包含了更改图像所需的代码。您可能需要对其进行一些调整,但这应该会让您走上正轨。如果您有任何问题,请告诉我。

于 2013-03-13T03:03:05.443 回答