2016-05-29 40 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;}')'''作品 –