访问量: 10 次浏览
创建一个使用jQuery的 <div> 元素可以通过以下步骤完成。
步骤:
<div> 元素。例子1:
这个例子创建了一个 <div> 元素,并使用 append() 方法将该元素追加到父元素的末端。
<!DOCTYPE html>
<html>
<head>
<title>
Create div element using jQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
#parent {
height: 100px;
width: 300px;
background: green;
margin: 0 auto;
}
#newElement {
height: 40px;
width: 100px;
margin: 0 auto;
color: white
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div id= "parent"></div>
<br><br>
<button onclick="insert()">
insert
</button>
<!-- Script to insert div element -->
<script>
function insert() {
$("#parent").append('<div id = "newElement">A '
+ 'Computer Science portal for geeks</div>');
}
</script>
</body>
</html>
输出:

* 点击该按钮后。

例子2:
这个例子创建了一个 <div> 元素,并使用 prependTo() 方法将该元素追加到父元素的开头。
<!DOCTYPE html>
<html>
<head>
<title>
Create div element using jQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
#parent {
height: 100px;
width: 300px;
background: green;
margin: 0 auto;
}
#newElement {
height: 40px;
width: 100px;
margin: 0 auto;
color: white
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div id= "parent"></div>
<br><br>
<button onclick="insert()">
insert
</button>
<script>
function insert() {
$('<div id = "newElement">A Computer Science portal'
+ ' for geeks</div>').prependTo($('#parent'));
}
</script>
</body>
</html>
输出:

* 点击该按钮后。
