这是一个由两部分组成的问题:
我有 2 个带复选框的部分。
- 我需要根据选中的复选框更新 url
- 我需要分享更新后的网址,该网址会在页面加载时打开并选中特定的复选框
我制作了一个带有 html 代码的 jsfiddle:https://jsfiddle.net/yh2ugbj8/5/
<h3>Filter recepies:</h3>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" id="cbox1" value="potato"> Potato</label><br>
<label><input type="checkbox" id="cbox2" value="onion"> Onion</label><br>
<label><input type="checkbox" id="cbox3" value="tomato"> Tomato</label><br>
</div>
<div>
<p>Select seasoning</p>
<label><input type="checkbox" id="cbox1" value="salt"> Salt</label><br>
<label><input type="checkbox" id="cbox2" value="pepper"> Pepper</label><br>
<label><input type="checkbox" id="cbox3" value="chilli"> Chilli Flakes</label><br>
</div>
最佳答案
我建议使用 location.hash
,这样您就可以在不离开页面的情况下将额外信息添加到 url。此信息也可以在链接中提供,以便您可以在首次导航到页面时检查所选元素...
HTML
<h3>Filter recepies:</h3>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" class="vegetables" value="potato"> Potato</label><br>
<label><input type="checkbox" class="vegetables" value="onion"> Onion</label><br>
<label><input type="checkbox" class="vegetables" value="tomato"> Tomato</label><br>
</div>
<div>
<p>Select seasoning</p>
<label><input type="checkbox" class="seasoning" value="salt"> Salt</label><br>
<label><input type="checkbox" class="seasoning" value="pepper"> Pepper</label><br>
<label><input type="checkbox" class="seasoning" value="chilli"> Chilli Flakes</label><br>
</div>
Javascript
$(function() {
$(".vegetables, .seasoning").on("change", function() {
var hash = $(".vegetables:checked, .seasoning:checked").map(function() {
return this.value;
}).toArray();
hash = hash.join("|");
location.hash = hash;
alert(hash);
});
if (location.hash !== "") {
var hash = location.hash.substr(1).split("|");
hash.forEach(function(value) {
$("input[value=" + value + "]").prop("checked", true);
});
}
});
这是一个更新的 fiddle ,其中页面 url 将值添加到哈希中...
https://jsfiddle.net/yh2ugbj8/6/
如您所见,我在脚本顶部添加了一行,以模拟访问附加了哈希值的页面。
我还删除了 ID 并向复选框添加了类,只是为了不让 jQuery 选择器变得丑陋。
注意:我添加了显示位置的警报,因为您不会看到 fiddle 示例更改 url,因为 4 个面板都是 iframe。
关于javascript - 根据使用 jquery/javascript 选择的复选框更新 url 而不重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36796480/