2015-02-11 39 views
1

我必須改變才能使其工作?jquery - 從選擇的數據屬性更改背景圖像

當我嘗試訪問$(this).data("image")時,它是undefined

HTML

<div id="imagecontainer"></div> 
    <select class="image"> 
     <option data-image="url(http:www.test.de/images/test1.jpg)">Image1</option> 
     <option data-image="url(http:www.test.de/images/test2.jpg)">Image2</option> 
     <option data-image="url(http:www.test.de/images/test3.jpg)">Image3</option> 
     <option data-image="url(http:www.test.de/images/test4.jpg)">Image4</option> 
    </select> 
</div> 

的jQuery:

$('.image').on('change', function() { 
    $("#imagecontainer").css("background-image", ($(this).data("image"))); 
}) 
+0

你應該先解釋一下你想要什麼工作和目前沒有。 – h7r 2015-02-11 22:07:22

回答

1

select元素沒有一個data-image屬性。孩子們option元素呢,所以你就必須選擇所選擇的選項元素:

$('option:selected', this).data("image"); 

或..

$(this).find('option:selected').data("image"); 
$('.image').on('change', function() { 
    $("#imagecontainer").css("background-image", ($('option:selected', this).data("image"))); 
}); 

Example Here

+0

作品。謝謝喬希! – 2015-02-11 22:07:09