2016-05-29 9 views
0

各要素について、CSSに動的にルールを追加したい。各ルールは異なる背景イメージと異なる名前を持つ必要があります。私はどこで間違いをしたのか分かりません。私はルールがさえCSSファイルにルールを動的に追加する

screenshot of google chrome developer tools

が付加されません

ルールはCSSファイルに追加されていると思いますが、IDを設定すると、動的に追加するCSSルールを動的に追加のdivをリンクしません...

$(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"); 
    } 
}); 
}); 
+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;}')'作品 –

関連する問題