2016-10-19 27 views
0

殘缺的圖像圖標我使用此代碼顯示和隱藏取決於下拉選擇圖片:jQuery的:在下拉列表中顯示的圖像選擇,使火狐

<html> 
<head> 
<script src="http://code.jquery.com/jquery-latest.pack.js"></script> 
</head> 
<body> 

<select id="my_select" name="select_name" class="order_form_select"> 
    <option data-img="" value="" disabled selected>Please select&nbsp;↓</option> 
    <option data-img="1.jpeg" value="first">First</option> 
    <option data-img="2.jpeg" value="second">Second</option> 
    <option data-img="3.jpeg" value="third">Third</option> 
</select> 

<img id="order_form_image" src=""> 

<script> 
document.getElementById("my_select").onchange = showFormatImage; 
function showFormatImage() { 
    $("#order_form_image").attr('src', $('select[name=select_name] option:selected').attr('data-img')); 
    $('#img_src').html($("#order_form_image").attr('src')); 
    return false; 
} 
</script> 

</body> 
</html> 

它的工作原理非常好。但在Firefox 48.0.1上,如果沒有下拉選項,我會看到一個破碎的圖標。下面是截圖:

broken image icon on firefox

爲什麼呢?我能做些什麼來防止它?

回答

0

一個簡單而快速的解決辦法是改變這個代碼添加到您的CSS:

img[src='']{ 
    display:none; 
} 

說明:只要沒有在下拉列表中選擇圖像時,圖像的名稱爲空。只要圖像名稱爲空,CSS代碼就會隱藏整個圖像標籤。

1

這是因爲您在加載時沒有設置源屬性。它只在觸發更改事件後才被設置。

隱藏元素,直到src被設置,然後取消隱藏。

+0

如何做到這一點? (我對JavaScript不太熟練) – David

+0

我找到了一個解決方案。 – David

相關問題