簡體   English   中英

使用Javascript更改下拉列表以選擇多個圖像?

[英]Changing a Drop Down list using Javascript to select multiple images?

我在網頁中有一個下拉列表,它當前所做的是顯示在列表中選擇的單個圖像。

我要實現的目標是,例如選擇一個區域(例如酒吧),它將顯示一組酒吧圖像而不是一個單獨的圖像,任何人都知道這樣做的嗎? 如果選擇其他選項,例如“大學”,它將顯示大學徽標的多個圖像。

即使我將其用作下拉列表,也可以將鼠標單擊超鏈接添加到圖像嗎?

我認為這是可能的,但是我找不到關於該主題的太多信息。

任何幫助都會很棒。

我的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
}

我不確定您的需求是什么,但是您不能直接在選擇選項上添加href屬性。

如果您只想在用戶選擇url時在其上添加url選項,則可以使用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更改內容。 如果提供了數據引用,則可以在圖像中添加<a></a>標簽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM