jQuery将CSS添加到变量

时间:2016-03-18 09:35:09

标签: javascript jquery

我有一个带有一些html的变量

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

如何向该变量添加一些内联css,如:

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

如果可能的话?

2 个答案:

答案 0 :(得分:2)

应用dom对象的css get outerHTML属性后。使用 filter() find() 取决于您的加价。

&#13;
&#13;
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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

或生成一个临时div并将字符串应用为html属性,然后在获取临时div的标记之后找到其中的id

&#13;
&#13;
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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分: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>