动态创建元素后,边框属性不起作用

时间:2018-07-19 06:38:16

标签: jquery css

我创建了一个div元素。在其中包装了一个文本框,然后更新了它的border属性,但是没有显示出来。这是什么问题?

var div =$('<div id="myDiv"></div>').css("border", "1px solid black");
$("#text1").wrap(div);
div.css("border", "1px solid red");
alert(div.css("border")); // it is showing 1px solid red

1 个答案:

答案 0 :(得分:0)

您的'div'只是变量,而不是元素。 使用ID代替:

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

此处提供了说明和正确的元素存储方式:

// here you create a object that has no connection to the dom
var div =$('<div id="myDiv"></div>').css("border", "1px solid black");

// here you add a object to the dom that has the same values as your object - but it's a seperate entity
$("#text1").wrap(div);

// here you only update your first object - it will never reflect on it's twin in the dom - 
// so remove this line:
// div.css("border", "1px solid red");

// so instead, save the real element to your variable
div = $("#myDiv");

// now you can work with it and it will update in the dom!
div.css("border", "1px solid red");

// you also need to know that since this is now a real div in your dom, you need to explicitly state which border you want:
// https://stackoverflow.com/questions/3787502/how-to-get-border-width-in-jquery-javascript
alert(div.css("border-left-color")); 

var div =$('<div id="myDiv"></div>').css("border", "1px solid black");
$("#text1").wrap(div);
div = $("#myDiv");
div.css("border", "1px solid red");
alert(div.css("border-left-color")); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text1">Text1</div>