【问题标题】:Javascript Hide/show section is not working on resetJavascript 隐藏/显示部分在重置时不起作用
【发布时间】:2014-07-02 16:39:22
【问题描述】:

我根据一些选项选择显示和隐藏一个 div。

有一个带有“启用和禁用”选项的下拉列表。一旦用户选择启用需要显示 div,否则隐藏 div。

基于下拉选项选择隐藏/显示 div 工作正常,但 如果禁用是配置的值。当我加载页面时,div将被隐藏(工作正常),然后我将选择启用,然后div显示但是......当我点击重置选项时, 下拉选项正在返回禁用,但应该隐藏的 Div 部分没有隐藏

我的代码是这样的,保护开关是从flask接收到的wtform字段

{{form.protection_switch}}
            <div align="center" >
            <button class="btn btn-info btn-sm" type="submit"><i class="icon-ok bigger-110"></i>Submit</button>
            &nbsp; &nbsp; &nbsp;
            <button class="btn btn-sm" type="reset"><i class="icon-undo bigger-110"></i>Reset</button>
            </div>

部分应该隐藏或显示

<div id="protection_data"></br> 
    <table id="grid-table"></table>
    <div id="grid-pager"></div>
</div>

jQuery 代码

function protection_selected() {
        if ($('#protection_switch option:selected').val() == '0') {
            $('#protection_data').hide();
        } else  if ($('#protection_switch option:selected').val() == '1') {
            $('#protection_data').show();
        }
    }

    $(document).ready(function() {
    $('#protection_switch').change(function() {
            protection_selected();
        });
    });
    window.onload = protection_selected;

【问题讨论】:

  • 使用jQuery时不要绑定window.onload = protection_selected;之类的事件。
  • 您能否详细说明在加载事件时绑定的替代方法是什么。请
  • $( window ).load(function() {protection_selected();});希望这很好

标签: javascript jquery html css jquery-ui


【解决方案1】:

监听点击重置。

function protection_selected() {
    var isVisible = $('#protection_switch').val() == '1';
    $('#protection_data').toggle(isVisible);
}

$(function(){  //document ready
    $("#protection_switch")  //get your select element
        .on("change", protection_selected)  //listen for change event
        .change();  //trigger the change event so defaults can be set
    $('input:reset').on("click", function(e){  //bind click event to reset button 
        this.form.reset();  //force reset so we guarantee it has finished running
        protection_selected();  //run the update code
        e.preventDefault();  //cancel the click since we already ran the reset code
    });
});

reset 后面的痛点是你可以检测到它何时调用,但它成功运行后没有任何事件。这就是为什么我捕获点击,在表单上运行重置,调用你的函数,并取消点击。另一种方法是在内部使用延迟而不是调用函数,但这可能导致竞争条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2012-12-29
    • 2020-08-25
    • 2016-05-24
    相关资源
    最近更新 更多