Javascript 添加所选属性jquery

Javascript 添加所选属性jquery,javascript,jquery,Javascript,Jquery,我想将所选属性添加到我的选择选项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=e

我想将所选属性添加到我的选择选项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");
});

分类
价格低廉
高价
流行的
$(“选择[name=sort]”)。更改(函数(){
window.location.href=$(this.val();
$(this.children().attr(“选定”、“选定”);
});
当我将所选选项更改为
Price Low
时,它会刷新页面并按最低价格排序,但该选项的值不会正确排序


我做错了什么

重新加载页面时,无法运行其他操作。这就像擦白板

元素的选择需要在页面加载时进行。您应该查看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
});

重新加载页面时,无法运行其他操作。这就像擦白板

元素的选择需要在页面加载时进行。您应该查看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
});

谢谢Epasarello的回答,但它仍然不起作用?@ChingChing尝试
这个.value
而不是
这个.text
哇,谢谢你更改了这个@ArunPJohny,迟到了!:)谢谢Epasarello的回答,但它仍然不起作用?@ChingChing尝试
这个.value
而不是
这个.text
哇,谢谢你更改了这个@ArunPJohny,迟到了!:)