Cannot read property 'style' of null

北城以北 提交于 2021-02-05 09:25:08

问题


Hi I am trying to hide a div when the page loads and display/hide it when a checkbox is checked/unchecked. This is my code:

<asp:CheckBox ID="cb1" runat="server" Text="CB" />

<div runat="server" id="div1" style="display:none">
</div>

And here is the javascript:

window.onload = function () {
    $('#cb1').change(function () {
        display('div1');
    })
}

function display(id) {
    var traget = document.getElementById(id);
    if (traget.style.display == "none") {
        traget.style.display = "block";
    } else {
        traget.style.display = "none";
    }
}

The error i get is this:

Uncaught TypeError: Cannot read property 'style' of null

This is the last version of my code. I have already tryed stuff like:

document.getElementById('div1').style.display="block";
$('#div1').hide();

... and many other options.

The result is the same. Please help


回答1:


You are using runat="server" so try this

<%= div1.ClientID %> 

to get the Id of the div and then you can call you function like this

display('<%= div1.ClientID %>');

or use clientidmode="static" in the markup

<div runat="server" id="div1" style="display:none" clientidmode="static">
</div>



回答2:


function display(id) {
    if ($('#'+id).css('display') === 'none') {
        $('#'+id).show();
    } else {
        $('#'+id).hide();
    }
}



回答3:


Try this

window.onload = function () {
    $('#<%= cb1.ClientID %>').change(function () {
        display('<%= div1.ClientID %>');
    })
}

function display(id) {
   $('#'+id).toggle();
}


来源:https://stackoverflow.com/questions/18441659/cannot-read-property-style-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!