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=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/

相关文章:

JavaScript 库,如果没有操作如何返回

javascript - Angular,用 settimeout 模拟 promise ($q)

javascript - 使用带有 html 的 javascript 自动光标像极地一样移动

javascript - 在 angularjs 中显示 6000 条记录时浏览器崩溃

javascript - 如何通过progressbar插件逆时针旋转饼图?

javascript - 如何检测 div 何时失去焦点?

jquery - slimScroll 与选择元素滚动问题

javascript - 用前缀替换外括号

javascript - Sweetalert2 Ajax - 发布输入数据

javascript - 将多行 var = false 代码压缩到更少的行?