我想添加所选属性到我的选择选项 HTML,我使用的选项值包含窗口位置 href 的链接。
<select name="sort">
<option value="">Sort</option>
<option value="category.php?c=electronic&sort=pricelow">Price Low</option>
<option value="category.php?c=electronic&sort=pricehigh">Price High</option>
<option value="categori.php?c=electronic&sort=popular">Popular</option>
</select>
$("select[name=sort]").change(function() {
window.location.href = $(this).val();
$(this).children().attr("selected","selected");
});
当我将所选选项更改为价格低
时,它会刷新页面并按最低价格排序,但选项的值不会正确排序。
我做错了什么?
最佳答案
重新加载页面时,您无法运行其他操作。这就像删除白板一样。
元素的选择需要在页面加载时进行。您需要查看 url 并将其与 select 元素相匹配。理想情况下,服务器端代码会选择它。
$(function(){ //on document ready
$("select[name=sort] option") //get the options
.filter( function () { //find the one that has the value that matches the url
return window.location.href.indexOf(this.value)>-1; //return true if it is a match
})
.prop("selected",true); //select it
});
关于javascript - 添加选定的属性jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420470/