在导航回来时,复选框未取消选中

时间:2014-05-29 05:56:50

标签: javascript php jquery html checkbox

我有以下代码,其中我在网址中添加带有哈希值的复选框值,但是当我从那里导航回来时,复选框没有被取消选中。请检查下面的代码

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>


<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car"> I have a car<br>

<script>
$checkboxes = $('input[type=checkbox');
$checkboxes.change(function(){
    window.location.hash = 'check=' + $checkboxes.filter(':checked').map(function(){
        return this.value;   
    }).get().join(",");
    console.log(window.location.hash);
});
</script>
</body>
</html>

我应该更改网址,以便在导航回来后取消选中复选框...

3 个答案:

答案 0 :(得分:0)

您正在寻找的是

$(window).on("hashchange", function() {
    // code here
}

然而,编写在每次散列更改时都不会清除复选框的代码可能会很棘手。

答案 1 :(得分:0)

更改以下代码:

$checkboxes = $('input[type="checkbox"]');

答案 2 :(得分:0)

Note: This is taken from another answer: http://stackoverflow.com/questions/10466648/

<label>
    <input type="checkbox" name="Vehicles[]" value="Bike"> I have a bike
</label>
<br />
<label>
    <input type="checkbox" name="Vehicles[]" value="Car"> I have a car
</label>
<br /> 

So if your form definition has the attribute: name="myform"
then you can do the following in javascript to uncheck the checkboxes:

var services = ​document.forms['myform']['Vehicles​[]']​;

for (var i = 0; i < Vehicles.length; i++) 
{
    Vehicles[i].checked = false;
}