简体   繁体   English

如果 URL 与值匹配,如何选择下拉列表?

[英]How to make dropdown selected if URL matched with value?

I'm trying to make a selection in the select box based on the URL.我正在尝试根据 URL 在select框中进行选择。 The urls are tied to the value attribute of option . url 与optionvalue属性相关联。 How can I do this in jQuery?我怎样才能在 jQuery 中做到这一点?

 <select> <option value="http://name.com/">All</option> <option value="http://name.com/category/electronics">Electronics</option> <option value="http://name.com/category/books">Books</option> <option value="http://name.com/category/furniture">Furniture</option> <option value="http://name.com/category/kitchen">kitchen</option> <option value="http://name.com/category/homeware">Homeware</option> <option value="http://name.com/category/outdoors">Outdoors</option> </select>

Maybe you want to bind the dropdown from the web URL.也许您想从 web URL 绑定下拉列表。 So you can add the id to your <select> tag like "drpCategory".因此,您可以将 id 添加到您的<select>标签中,例如“drpCategory”。 Now you need to add below script for auto-selection of your dropdown.现在您需要添加以下脚本以自动选择下拉列表。

$(function(){
   $("#drpCategory").val(window.location.href);
});

Put this code immediately after your <select> block:将此代码紧跟在 <select> 块之后:

<script>
$('select').last().val(location.href)
</script>

$('select').last() is jQuery's way to select the preceeding <select> element in the document. $('select').last() 是 jQuery 选择文档中前面的 <select> 元素的方法。 .val(value) is jQuery's way of changing the selection to the option with the specified value. .val(value) 是 jQuery 将选择更改为具有指定值的选项的方法。 By passing location.href to.val() you are telling it to select the option whose value contains the full URL of the current page.通过将 location.href 传递给 .val(),您告诉它选择其值包含当前页面的完整 URL 的选项。

At first, get the pathname from the URL you're currently in. You can do this with this function: window.location.pathname .首先,从您当前所在的 URL 获取pathname 。您可以使用以下函数执行此操作: window.location.pathname Then in javascript code check if your pathname matches any of the options value and if it does then add selected attribute on that option.然后在 javascript 代码中检查您的pathname是否与任何options值匹配,如果匹配则在该选项上添加selected属性。

If you just need to select an option on page load then the following should do it.如果您只需要在页面加载时选择一个选项,那么应该执行以下操作。

$(function(){
   $( "select").val(window.location);
))

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

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