2013-01-14 81 views
0

我在網頁中有一個下拉列表,它當前所做的是顯示在列表中選擇的單個圖像。使用Javascript更改下拉列表以選擇多個圖像?

我想要實現的是如果選擇了某個扇區(例如酒吧),它將顯示一組酒吧圖像而不是一個人圖像,任何知道這樣做的人?如果我選擇另一個選項,如大學,它會顯示大學徽標的多個圖像。

也有辦法添加一個鼠標點擊超鏈接到圖像,即使我使用它作爲下拉列表?

我認爲這是可能的,但我無法找到關於這個問題的很多信息。

任何協助將是偉大的。

我的HTML代碼:

<table border="0" cellspacing="0" cellpadding="0"> 
    <tr> 
     <td width="100%"> 
      <form name="mygallery"> 
       <p> 
        <select name="picture" size="1" onChange="showimage()"> 
         <option selected value="gfx/Marstons.jpg">Marstons pubs</option> 
         <option value="gfx/NorthUni.jpg" href="http://www.northumbria.ac.uk/">Northumbria University</option> 
        </select> 
       </p> 
      </form> 
     </td> 
    </tr> 
    <tr> 
     <td width="100%"> 
      <p align="center"> 
       <img src="gfx/Marstons.jpg" name="pictures" width="99" height="100"> 
     </td> 
    </tr> 
</table> 

我的JavaScript

function showimage() { 
    if (!document.images) return 
    document.images.pictures.src = document.mygallery.picture.options[document.mygallery.picture.selectedIndex].value 
} 

回答

1

我不知道什麼是你需要的,但你不能在選擇選項直接添加href屬性。

如果您只想添加url上的url選項以在用戶選擇它時將其應用於img,則可以使用html5提供的data- *屬性。

下面是您在請求中提供的代碼示例。

JS搗鼓現場測試:HTTP://jsfiddle.net/BVAkh/1/

HTML部分:

<html> 
    <head></head> 
    <body> 
    <table border="0" cellspacing="0" cellpadding="0"> 
    <tr> 
     <td width="100%"> 
      <form name="mygallery"> 
       <p> 
        <select name="picture" size="1" onChange="javascript:showimage()"> 
         <option selected value="gfx/Marstons.jpg">Marstons pubs</option> 
         <option value="gfx/NorthUni.jpg" data-href="http://www.northumbria.ac.uk/">Northumbria University</option> 
        </select> 
       </p> 
      </form> 
     </td> 
    </tr> 
    <tr> 
     <td width="100%"> 
      <p align="center"> 
       <img src="gfx/Marstons.jpg" name="pictures" width="99" height="100" /> 
      </p> 
     </td> 
    </tr> 
</table> 
     </body> 
    </html> 

的js部分:

function showimage() { 
    if (!document.images) return; 
    var selectedItem = document.mygallery.picture.options[document.mygallery.picture.selectedIndex]; 
    document.images.pictures.src = selectedItem.value; 

    if(selectedItem.getAttribute("data-href")) { 
     document.images.pictures.onclick = function() { 
     window.location.href = selectedItem.getAttribute("data-href"); 
     } 
    } 
    else { 
     document.images.pictures.onclick = null; 
    } 
} 

但我認爲你應該重新考慮圖像變化。也許給你的p設置一個id,然後用innerHTML改變內容。如果提供了data-href,您將能夠爲圖像添加一個<a></a>標籤。

+0

在javascript中使用隱藏顯示。要顯示每個部門(如「酒吧」)的div。 – user1259076

相關問題