2016-03-18 75 views
0

我有一個變量,一些HTMLjQuery的CSS添加到變量

var myvar = '<div id="myid">something here</div>'; 

如何添加一些CSS內嵌到這樣的變量:

$(myvar).css("border","1px solid red"); 

如果這可能嗎?

+0

你會用這個結果做什麼? – itzmukeshy7

回答

2

您的代碼工作正常

var myvar = '<div id="myid">something here</div>'; 
 

 
myvar = $(myvar).css({ 
 
    "border":"1px solid red", 
 
    "color": "blue" 
 
}); 
 

 
$(myvar).appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

,但如果你想用你的id選擇器應用CSS,你需要將myvar追加到DOM FIRST

var myvar = '<div id="myid">something here</div>'; 
 
$(myvar).appendTo("body"); 
 
myvar = $("#myid").css({ 
 
    "border":"1px solid red", 
 
    "color": "blue" 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2

應用css後得到outerHTML屬性的dom對象。使用filter()find()取決於您的標記。

var myvar = '<div id="myid">something here</div>'; 
 
myvar = $(myvar) 
 
    //get element with id 
 
    .filter('#myid') 
 
    // apply css ,     
 
    .css("border", "1px solid red") 
 
    // go back to previous selector and get dom object 
 
    .end()[0] 
 
    // get outerHTML property of dom object 
 
    .outerHTML; 
 

 
console.log(myvar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


或生成一個臨時股利和應用的字符串作爲HTML屬性,然後發現裏面的ID,得到暫時的div標記後

var myvar = '<div id="myid">something here</div>'; 
 
// generate div with html content as string 
 
myvar = $('<div/>', { 
 
    html: myvar 
 
    }) 
 
    // get id element from it 
 
    .find('#myid') 
 
    // apply css 
 
    .css("border", "1px solid red") 
 
    // go back to previous selector 
 
    .end() 
 
    // get html content of temporary div 
 
    .html(); 
 

 
console.log(myvar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

+0

我需要將內聯樣式添加到id myid,因爲我可能想要定位的字符串中有其他div – Satch3000

+0

@ Satch3000:已更新 –