2016-05-29 50 views
0

对于我想动态添加规则到CSS的每个元素。每个规则应该有不同的背景图像和不同的名称。不知道我犯了什么错误。我认为规则添加到CSS文件,但设置ID不符合动态添加CSS规则链接动态添加的div ...将规则动态添加到CSS文件

$(document).ready(function() { 

var stylesheet = document.styleSheets[0]; 

var url = '/Home/PrikaziTipoveLokacija'; 

//this gets all the data from database and it works fine 
$.ajax({ 
    type: "GET", 
    url: url, 
    cache: false, 
    success: function (data) { 
     //Checking number of rules in my CSS with this loop before adding new rules 
     for (var i = 0; i < stylesheet.cssRules.length; i++) { 
      count++; 
     } 
     alert(count); //this returns count 16 (CSS files has 16 rules) 
     count = 0;    

     //this loop should add a rule to CSS for each element in data. I have set the same image for every element for now. 
     for (elem in data) { 
      if (stylesheet.addRule) { 
       stylesheet.addRule(data[elem].Kljuc + '_ikona', '{ background-image: url("../Images/mesnicaicon.png"); background-size: cover; background-repeat:no-repeat;}'); 
      } else if (stylesheet.insertRule) { 
       stylesheet.insertRule(data[elem].Kljuc + '_ikona' + '{' + 'background-image: url("../Images/mesnicaicon.png"); background-size: cover; background-repeat:no-repeat;' + '}', stylesheet.cssRules.length); 
      } 
     } 

     //Checking number of rules in my CSS with this loop after adding new rules 
     for (var i = 0; i < stylesheet.cssRules.length; i++) { 
      count++; 
     } 
     alert(count); //this returns count 33, therefore , the new rules are added (Data has 17 elements, so, 33-16=17) 
     count = 0; 


     for (elem in data) { 
      var div = document.createElement('div'); 


      div.className = 'ikona'; //irrelevant class 
      div.id = data[elem].Kljuc + '_ikona'; //for each element set different id depending on the attribute 'Kljuc' from database 

      var onclick = document.createAttribute("onclick"); 
      onclick.value = 'prikaziTipLokacije('+ data[elem].ID +')'; 
      div.setAttributeNode(onclick); 

      div.innerHTML = data[elem].Naziv; 

      document.getElementById('izbornik_za_lokacije').appendChild(div); 
     } 



    }, 
    error: function() { 
     alert("Greška pri dohvaćanju tipova lokacija"); 
    } 
}); 
}); 

规则甚至没有附加

screenshot of google chrome developer tools

+0

您是否为新规则添加了散列符号#以标识id值? –

+0

是的,这是问题所在。谢谢! – Fale1994

回答

1
var style = document.createElement('style'); 
style.innerHTML = '*{ color:red; } /* put your stuff here */'; 
document.body.appendChild(style); 

创造新的风格元素,并使用它

在SO只是测试(从控制台上运行)和它的作品

document.styleSheets[0].insertRule('* { color: red; }') 
+0

谢谢你的回答,它的工作。但是我仍然对我在添加规则到现有的外部CSS文件 – Fale1994

+0

只是在SO'document.styleSheets [0] .insertRule('* {color:red;}')'''作品 –

相关问题