【问题标题】:On navigating back,checkbox not getting unchecked在导航回来时,复选框没有被取消选中
【发布时间】:2014-05-29 05:56:50
【问题描述】:

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

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

我应该在 url 中更改什么以在导航回来后取消选中复选框...

【问题讨论】:

  • 你有没有通过'tidy'运行你的代码?为了提供帮助, 标签必须与 标签配对,或者在标签内容的末尾用“/>”自封闭。另一个细节,
    需要结束 或(最好写成)
    。输入标签没有文本组件,所以使用标签标签。不幸的是,大多数浏览器只是猜测想要什么,而不是遵守 html 规则。
  • 两者的输入类型=checkbox,同名=“vehicle”。这些不是单选按钮,因此除非名称是数组,否则所有名称都应该是唯一的。

标签: javascript php jquery html checkbox


【解决方案1】:

你要找的是

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

但是,编写在每次哈希更改时不清除复选框的代码可能会很棘手。

【讨论】:

    【解决方案2】:

    修改如下代码:

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

    【讨论】:

    • 仅在该行中进行更改...重复代码将相同
    【解决方案3】:
    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多