2015-04-04 81 views
1

我試圖複製this simple example,但因爲我的生活無法正常工作。第一張照片顯示,但不會改變。原諒我,如果這是基本的,我很新的JavaScript。在下拉列表中更改圖片javascript/jquery

<html> 
<head> 
    <script src="/js/jquery-1.11.2.js"></script> 
    <script type="text/javascript"> 
    var pictureList = [ 
     "http://lorempixel.com/400/200/sports/1", 
     "http://lorempixel.com/400/200/sports/2", 
     "http://lorempixel.com/400/200/sports/3", 
     "http://lorempixel.com/400/200/sports/4", 
     "http://lorempixel.com/400/200/sports/5", ]; 

    $('#picDD').change(function() { 
     var val = parseInt($('#picDD').val()); 
     $('img').attr("src",pictureList[val]); 
    }); 

    </script> 
</head> 
<body> 
    <img src="http://lorempixel.com/400/200/sports/1" /> 
    <select id="picDD"> 
     <option value="1" selected>Picute 1</option> 
     <option value="2">Picute 2</option> 
     <option value="3">Picute 3</option> 
     <option value="4">Picute 4</option> 
     <option value="5">Picute 5</option> 
    </select> 
</body> 
</html> 

回答

3

您需要將您的代碼:

// A $(document).ready() block. 
$(document).ready(function() { 
    // Your code here. 
}); 

否則你的代碼不會工作。在的jsfiddle你可以在左邊的JavaScript看到的是加載onDomready

+0

啊啊,謝謝。 – pythonismyjam 2015-04-04 20:15:19

0
$(document).ready(function() { 
    $('#picDD').change(function() { 
     var val = parseInt($('#picDD').val()); 
     $('img').attr("src",pictureList[val]); 
    }); 
}); 

在的jsfiddle,你沒有,因爲它是動態的指定文件準備好功能。試試這個,它應該適合你。