2015-07-21 84 views
0

我有一個下拉菜單。如何從下拉菜單中選擇某個選項時觸發某些內容?

在更改時,我想重定向到某個URL。

我不知道我該怎麼做。

我試圖檢查,看看是否值==類視

if($('#dd').val() === "class-view"){ 

    location.href = "www.site.com"; 
} 

現在,它不斷循環並刷新我的網頁。

+0

在選擇事件監聽器中有'if'語句 – depperm

+2

您正在尋找'change'事件...現在我可以問你有多少個puppet帳戶? http://stackoverflow.com/questions/31525520/how-can-i-redirect-to-specific-url-on-select-change#comment51012421_31525520 –

回答

1

您的頁面正在循環,因爲加載頁面的加載時間,所選值爲「class-view」,因爲它是選擇列表中的第一個選項。嘗試使用jquery做這樣的事情。

$(document).ready(function(){ 
    $("#rn-dd").change(function(){ 
     var selectedVal = $(this).val(); // Value of the selected option 
     // Redirect to your page accordingly 
    }); 
}); 

您可以添加data-href屬性,每一個選項,以便您可以重定向到該位置時的變化具有happened.So你的HTML應該是這樣的

<select class="rn-dropdown" id="rn-dd"> 
    <option value="class-view" data-href="a.html">class view</option> 
    <!-- Students Populate Here --> 
    <option id="s-00586" data-href="b.html" value="s-00586">Student S00586</option> 
    <option id="s-00587" data-href="c.html" value="s-00587">Student S00587</option> 
    <option id="s-00588" data-href="d.html" value="s-00588">Student S00588</option> 
    <option id="s-00589" data-href="e.html" value="s-00589">Student S00589</option> 
    <option id="s-00590" data-href="f.html" value="s-00590">Student S00590</option> 
</select> 

現在你可以在href數據所選選項的屬性值。因此,完整的解決方案會是這樣,

$(document).ready(function(){ 
    $("#rn-dd").change(function(){ 
     document.location.href = $(this).find(":selected").data("href"); 
    }); 
}); 

你可以找到更多有關數據從這裏Jquery Data attribute

+0

如何將具體的行動應用到每個選項?我仍然會使用相同的代碼嗎?感謝您的幫助。 :) –

+1

在你的答案中,id不能解釋「href」和「s5」變量是什麼。所以說它是否正確並不容易。但是,對於你正在尋找的東西,可能有一個快速解決方案。我編輯了我的答案,查看它! –

+0

非常感謝您的更新。這會幫助我很多。 –

0

屬性在onchange事件testMessage功能將得到調用,把你的邏輯在這個函數內。

<script type="text/javascript"> 
    $("#rn-dd").change(function() { 
     var selectedText = $(this).find("option:selected").text(); 
     var selectedValue = $(this).val(); 
     alert("Selected Text: " + selectedText + " Value: " + selectedValue); 
     if(selectedText == "" && selectedValue == "") { // placed your here for different action on different selected options. 
      // do something 
     } 
    }); 
</script> 

編輯:

你應該閱讀這JQuery - OnChange Event。會有幫助。

+0

如何將具體操作應用於每個選項?我仍然會使用相同的代碼嗎?感謝您的幫助。 :) –

+0

@TiffanySoun更新了答案。 –

相關問題