简体   繁体   English

jQuery选择框根据URL选择选项

[英]jQuery select box make option selected based on url

I have a select box as follows. 我有一个选择框,如下所示。 How do i mark an option as selected based on the last part of the url. 如何根据网址的最后部分将选项标记为已选中。 ex: http://domain.com/index/one . 例如: http : //domain.com/index/one The last part of the url is one so i want option one to be selected. 网址的最后一部分是一个,因此我希望选择一个选项。

<select>
    <option id="one">One</option>
    <option id="two">Two</option>
    <option id="three">Three</option>
</select>

I'm looking for jQuery or Javascript Solution. 我正在寻找jQuery或Javascript解决方案。

I think this should do, assuming URL has that last part you mentioned ('one' as in your question) 我认为应该这样做,假设URL具有您提到的最后一部分(如您的问题中的“一个”)

$('#selectid').val(window.location.href.substring(
                      window.location.href.lastIndexOf('/')+1))
var parts = window.location.href.split('/');
if (parts.length > 0) {
    $('#myselect').val(parts[parts.length - 1].split('?')[0]);
}

also make sure you fix your select and give values to your options, not ids: 还请确保您修正了选择内容,并为选项(而非ID)提供了值:

<select id="myselect">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select>

Is there a reason why you're trying to do this with jquery/javascript? 您为什么要尝试使用jquery / javascript执行此操作? would seem more logical to do this with whatever server side language you're using. 使用您使用的任何服务器端语言似乎更合乎逻辑。 Maybe use a rewrite as well. 也许也可以使用重写。

I guess you are looking for: window.location Maybe parse a range from that url. 我猜您在寻找: window.location可能从该URL解析一个范围。

Sample: http://jsfiddle.net/R48GY/ 范例: http//jsfiddle.net/R48GY/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM