简体   繁体   English

document.querySelector(“。class h1”)

[英]document.querySelector(“.class h1”)

I'm working on my schools webpage, and i'm trying to select all header elements inside a div with a class called "text" using the querySelector(String) function - and then changing the headers background, border, and text colour, but the following code doesn't seem to work 我正在学校的网页上工作,并且尝试使用querySelector(String)函数选择一个名为“ text”的类的div中的所有标题元素,然后更改标题的背景,边框和文本颜色,但是以下代码似乎不起作用

var test = "content.html #test"
$(document).ready(function()
{
    $.ajax(
    {
        success : function(data)
        {                   
            $("#content").load(test); //this works - loads <div id="test"> and all elements within it from content.html
            document.querySelector(".content").style.backgroundColor = "#CCFFCC"; //this works - exists inside main html file ( $(document) )
            document.querySelector(".text h1").style.backgroundColor = "#CCFFCC"; //this doesn't work - still loading default colour from css
            document.querySelector(".text h1").style.color = "#003300"; //this doesn't work - still loading default colour from css

//Appropriate close tags follow...

Would you guys know what i'm doing wrong? 你们知道我在做什么错吗? Am I referencing my elements in the wrong way? 我是否以错误的方式引用了我的元素? or does it have something to do with the fact that i'm trying to dynamically load this content from a separate file? 还是与我试图从单独的文件动态加载此内容有关? Or something else entirely? 还是完全其他?

As Klaster_1 intimated, you need to utilize load 's callback functionality. 正如Klaster_1暗示的那样,您需要利用load的回调功能。

$('#content').load(test, function() {
    document.querySelector(".content").style.backgroundColor =    "#CCFFCC";
    document.querySelector(".text h1").style.backgroundColor = "#CCFFCC"; 
    document.querySelector(".text h1").style.color = "#003300"; 
});

What Klaster_1 means when he says it's an "async" operation is that it runs out of sync of the rendering of the DOM. Klaster_1所说的“异步”操作是指它与DOM呈现不同步。 In other words, that code styling the content will be run before the browser's run loop has a chance to actually put the content on the page. 换句话说,样式化内容的代码将在浏览器的运行循环有机会将内容实际放置到页面之前运行。

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

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