如何使用jQuery检测和改变一个div的内容/样式
一个div的html/text的变化可以通过jQuery on()方法来检测。on()是用来附加一个或多个事件处理程序给DOM树中的选定元素和子元素。on()方法替代了jQuery 1.7版本中的bind(), live()和delegate()方法。
语法:
$(selector).on(event, childSelector, data, function, map)
例子1:这个例子使用jQuery on()方法来改变文本的 <div>
元素。
<!DOCTYPE html>
<html>
<head>
<title>
How to detect and change the
content of a div using JQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
#div1 {
font-size: 35px;
color:green;
text-align:center;
}
</style>
<script>
(document).ready(function(){
("div").on("click", function(){
document.getElementById("div1").innerHTML
= "A computer science portal for geeks";
});
});
</script>
</head>
<body>
<div id="div1">GeeksforGeeks!</div>
</body>
</html>
输出:
- 在点击div元素之前。
- 点击div元素后。
例子2:这个例子使用jQuery on()方法来改变一个<div>
元素的样式。
<!DOCTYPE html>
<html>
<head>
<title>
How to detect and change the
style of a div using JQuery?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
#div1 {
font-size: 35px;
color:green;
text-align:center;
}
</style>
<script>
(document).ready(function(){
("div").on("click", function(){
document.getElementById("div1").style.color
= "white";
document.getElementById("div1").style.backgroundColor
= "green";
});
});
</script>
</head>
<body>
<div id="div1">Welcome to GeeksforGeeks!!!</div>
</body>
</html>
输出:
- 在点击div元素之前。
- 点击div元素后。