2016-08-15 17 views
1

我試圖從兩個選擇字段構建圖像路徑。我必須使用「id」,因爲已經使用了「value」。不幸的是只有第二選擇作品。有沒有人有提示?正如你可能看到我不是一個編碼器。任何人都可以如此善良,並幫助使代碼更優雅/苗條? 當用戶改變他的選擇時,我使用onchange來更新「result1」和「result2」。 由於提前,喬治·如何使用Javascript從兩個選擇/選項ID構建圖像名稱/路徑

這裏是我的代碼:

<script> 
 
    function showOptions1(s) { 
 
    document.getElementById("result1").innerHTML = "<img src='img/preview/" + s[s.selectedIndex].id; 
 
} 
 
</script> 
 
<script> 
 
    function showOptions2(s) { 
 
    document.getElementById("result2").innerHTML = s[s.selectedIndex].id + ".jpg'>"; 
 
} 
 
</script>
<select onchange="showOptions1(this)" id="my_select1"> 
 
    <option value="werta" id="1">Text Item 1a</option> 
 
    <option value="wertb" id="2">Text Item 1b</option> 
 
</select> 
 

 
<select onchange="showOptions2(this)" id="my_select2"> 
 
    <option value="wertc" id="3">Text Item 1c</option> 
 
    <option value="wertd" id="4">Text Item 1d</option> 
 
</select> 
 

 
<span id="result1"></span><span id="result2"></span>

回答

0

,因爲你希望用戶構建路徑之前選擇兩件事情我不會用onchange事件。因此,在屏幕上放置另一個名爲「保存圖像」的按鈕或類似的東西。此按鈕的onclick獲取每個選擇輸入的「值」並將它們連接在一起。你可以很容易地得到使用jQuery的選擇輸入的名字

var select1 = $("#my_select1"); 

現在你的問題是,你不想要的價值。那很簡單。相反,你需要選擇選項,然後你想獲得ID。你可以這樣做,如下所示

var my1id = $("#my_select1 option:selected").id; 
+0

你應該使用'[0] .id' –

+0

是,正確,謝謝。在使用點之前,您必須從jquery獲取原始DOM對象。所以這將是var my1id = $(「#my_select1選項:選中」)[0] .id; – javaMoca

0

非常感謝您的支持。乾杯喬治

Finaly我用這個代碼(並堅持的onchange因爲我不想另一個按鈕,因爲有媒體鏈接他們三人):

<script> 

    var selection01, selection02; 

    showOptions1 = function(s) { 

     selection01 = "<img src='img/preview/" + s[ s.selectedIndex ].id; 

     getResult(); 


    }; 

    showOptions2 = function(s) { 

     selection02 = s[ s.selectedIndex ].id + ".jpg' width='200px;'>"; 

     getResult(); 

    }; 

    function getResult() { 

     var total = selection01 + selection02; 

     console.log(total); 

     document.getElementById("Image").innerHTML = total; 

    }; 

</script> 

<select id="select1" onchange="showOptions1(this)"> 
    <option value="" id="01" selected>...</option> 
    <option value="werta" id="10">Text Item 1a</option> 
    <option value="wertb" id="20">Text Item 1b</option> 
</select> 

<select id="select2" onchange="showOptions2(this)"> 
    <option value="" id="02" selected>...</option> 
    <option value="wertc" id="30">Text Item 1c</option> 
    <option value="wertd" id="40">Text Item 1d</option> 
</select> 

<hr><span id="Image"></span> 
相關問題