2017-02-21 83 views
-1

嘿有没有办法在javascript中添加类到尚未激活的元素?我用将css添加到不存在的类

$(".myelement).attr('class', 'myelement toast'); 

myelement不会出现在我的代码中,所以这个类是不会应用,直到我启动它一次?

+0

*未激活但* - 隐藏或不存在的? – RomanPerekhrest

+0

元素添加到'document'的位置? – guest271314

+0

直到我使用添加新代码的模块才会出现! – psppro26

回答

0

检查:

let exist = false; 
 
document.body.addEventListener("DOMSubtreeModified", function() { 
 
// http://caniuse.com/#search=DOMSubtreeModified 
 

 
    // warning : this will run everytime the dom modified 
 
    // this check will prevent unwanted loops 
 
    if(!exist) { 
 
    setTimeout(function() { 
 
     const theDiv = document.getElementById('theDiv'); 
 
     if(theDiv && !exist) { 
 
     exist = true; 
 
     console.log("It is right there, let's add a class to it"); 
 
     
 
     // add some delay (not a must, just to follow easily) 
 
     setTimeout(function() { 
 
      theDiv.setAttribute('class', theDiv.getAttribute('class')+' cool'); 
 
      console.log('done!') 
 
     },1000); 
 
     } 
 
    },0); 
 
    } 
 
}); 
 

 
console.log("Waiting 2 seconds..."); 
 

 
// delay to follow things easily 
 
setTimeout(function() { 
 
    console.log("Creating a div.."); 
 
    let newDiv = document.createElement('div'); 
 
    newDiv.innerHTML = 'Cool!'; 
 
    newDiv.setAttribute('id','theDiv'); 
 
    document.body.appendChild(newDiv); 
 
    console.log("Created."); 
 
},2000);
.cool { 
 
    background-color: red; 
 
    color: white; 
 
    font-weight: bold; 
 
}

2

绝对正确:您将无法将属性,数据,属性等添加到尚未在DOM中的元素。

每次创建“.myelement”节点并添加到页面时,您都需要执行该调用。

顺便说一下,对于CSS类,不要使用“attr” - 使用jQuery's class methods来代替。

希望这会有所帮助!