简体   繁体   English

添加选定的属性jQuery

[英]Add selected Attribute jquery

I want to add the selected attribute to my select option HTML, I'm using an option value which has a link the window location href. 我想将selected属性添加到我的选择选项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");
});

When I change the selected option to Price Low , it refreshes the page and sorts by lowest price, but the option's value will not sorted properly. 当我将选定的选项更改为Price Low ,它将刷新页面并按最低价格排序,但该选项的值将无法正确排序。

What am I doing wrong? 我究竟做错了什么?

When you reload the page, you can not run another action. 重新加载页面时,无法运行其他操作。 It is like erasing the whiteboard. 这就像擦除白板一样。

Selecting of the element would need to occur on the load of the page. 选择该元素将需要在页面加载时进行。 You would beed to look at the url and match it to the select element. 您不妨查看一下url并将其与select元素匹配。 Ideally the serverside code would select it. 理想情况下,服务器端代码会选择它。

$(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
});

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

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