简体   繁体   English

强制javascript在aspx页面加载上运行

[英]Force javascript to run on aspx page load

I have a aspx page with some databound controls. 我有一个带有一些数据绑定控件的aspx页面。 One of them is a checkbox. 其中一个是复选框。 If this checkbox is checked then it should show a div, else hide it. 如果选中此复选框,则它应显示一个div,否则将其隐藏。 It works great when I click/unclick the box. 当我单击/取消单击该框时,效果很好。 BUT, when the page loads initially the div ALWAYS shows up until I check/uncheck the checkbox. 但是,当页面最初加载时,div始终显示,直到我选中/取消选中该复选框。 How can I fix this so that if the databound checkbox is not checked then when the page loads the div is hidden? 如何解决此问题,以便如果未选中数据绑定复选框,则在页面加载时div被隐藏?

<script type="text/javascript">
   function hideDiv(obj) {
        if (obj.checked == true) {
            document.getElementById("divHome").style.display = 'block';
        }
        else {
            document.getElementById("divHome").style.display = 'none';

        }
    }
</script>
<asp:CheckBox ID="cbMycb" runat="server" ClientIDMode="Static" onClick="hideDiv(this);"
    Checked='<%# Bind("MyField") %>' />
<br />
<div id='divHome'>
        STUFF INSIDE THE DIV
</div>

You can either run the hideDiv function when the content is loaded as Amit Joki stated. 加载内容后,您可以按照Amit Joki的说明运行hideDiv函数。

    window.onload =function(){
    hideDiv(document.getElementById('cbMycb'));

But, this solution might present a little issue, you might see the div flickers when the page loads if the div is visible. 但是,此解决方案可能会出现一个小问题,如果div可见,则您可能会在页面加载时看到div闪烁。 To solve it just make sure the div is not visible by default by adding some css style... 要解决此问题,只需添加一些CSS样式,以确保默认情况下div不可见...

#divHome{
    display: none;
}

Another approach would be using a conditional databinding expression to set the div's visibility... 另一种方法是使用条件数据绑定表达式来设置div的可见性...

<div id='divHome' style='<%# "display:" +  ((bool)Eval("MyField") ? "block" : "none") %>'>
        STUFF INSIDE THE DIV
</div>

Hope it helps 希望能帮助到你

Just call your function once outside. 只需在外面调用一次函数即可。

<script type="text/javascript">
   function hideDiv(obj) {
        if (obj.checked == true) {
            document.getElementById("divHome").style.display = 'block';
        }
        else {
            document.getElementById("divHome").style.display = 'none';

        }
    }
    window.onload =function(){
        hideDiv(document.getElementById('cbMycb'));
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM