如何使用jQuery检测和改变一个div的内容/样式

如何使用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元素之前。
    如何使用jQuery检测和改变一个div的内容/样式?
  • 点击div元素后。
    如何使用jQuery检测和改变一个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元素之前。
    如何使用jQuery检测和改变一个div的内容/样式?
  • 点击div元素后。
    如何使用jQuery检测和改变一个div的内容/样式?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程