简体   繁体   English

style.display ='block'无法在div上使用javascript

[英]style.display = 'block' not working in javascript on a div

I am trying to Add a DIV which has a image source in it to an HTML. 我正在尝试将包含图像源的DIV添加到HTML中。 and after i am trying to change the property of above added DIV. 在我试图改变上面添加的DIV的属性之后。 But i am not able to do so. 但我无法这样做。 The DIV is showing up in the Browser Development tools when checked. 选中后,DIV将显示在浏览器开发工具中。 The Error i am getting is "Cannot read property 'style' of null". 我得到的错误是“无法读取null的属性'样式”。 Below is my code. 以下是我的代码。 Thanks in advance. 提前致谢。

ajaxLoaddiv='<div class="LoadingImage" alt="example" style="display: none"> <img src="css/ajax-loader.gif"></div>';
$(ajaxLoaddiv).appendTo(attachPoint);
document.getElementById("LoadingImage").style.display = 'block'; 

attachpoint is a reference in the html which i got by. attachpoint是我得到的html中的引用。

var attachpoint=document.querySelector('.buttonAttachPoint');

You gave it class='LoadingImage' , but not id='LoadingImage' and later attempt to retrieve it with getElementById("LoadingImage") . 你给它class='LoadingImage' ,但不是id='LoadingImage' ,后来尝试用getElementById("LoadingImage")检索它。 Just add the id attribute. 只需添加id属性即可。

ajaxLoaddiv='<div id="LoadingImage" class="LoadingImage" alt="example" style="display: none"> <img src="css/ajax-loader.gif"></div>';
//--------------^^^^^^^^^^^^^^^^^^^

But if you are already using jQuery, you might as well use it here too. 但是如果你已经在使用jQuery,那么你也可以在这里使用它。

$('#LoadingImage').css('display', 'block');

...And could therefore more easily access it by class (assuming this is the only element with the class LoadingImage ) if you prefer: ...因此,如果您愿意,可以更容易地通过类访问它(假设这是具有类LoadingImage的唯一元素):

$('.LoadingImage').css('display', 'block');

document.getElementById gets the element by ID, not class? document.getElementById按ID获取元素,而不是类?

var ajaxLoaddiv = $('<div />', {'class': 'LoadingImage',
                                 alt   : 'example',
                                 style : 'display: none'
                                }),
    img = $('<img />', {src: 'css/ajax-loader.gif'});

ajaxLoaddiv.append(img).appendTo(attachPoint);
ajaxLoaddiv.show();

use: 采用:

$("#LoadingImage").css({"display": "block"});

If you want a jQuery solution :) 如果你想要一个jQuery解决方案:)

Also, you used a class name instead of the element's ID 此外,您使用了类名而不是元素的ID

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

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