JavaScript DHTML/jQuery/this

Материал из Web эксперт
Перейти к: навигация, поиск

this pointer

   <source lang="html4strict">
   

<html>

 <head>
   <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
   <script type="text/javascript">
   $(document).ready(function(){
       var str = $(this).text();
       alert(str)
   });
   </script>
 </head>
 <body>
A
B
C
D
 </body>

</html>



 </source>
   
  


Use jQuery object instead of the regular DOM element, use the $(this) function

   <source lang="html4strict">

<html>

 <head>
   <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
   <script type="text/javascript">
       $(document).ready(function(){
               $("span").click(function () {
                  $("li").each(function(){
                     $(this).toggleClass("example");
                  });
               });
       });
   </script>

<style>

.example { font-style:italic; }
 

</style>

 </head>
 <body>
   <body>
      To do list: (click here to change)
  • A
  • B
  • C
   </body>

</html>

 </source>
   
  


Use this to reference document

   <source lang="html4strict">
   

<html>

 <head>
   <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
   <script type="text/javascript">
       $(document).ready(function(){
$("p").replaceWith("
" + $(this).text() + "
");
       });
   </script>
   <style>
     div { border:2px green solid;}
   </style>
 </head>
 <body>
   <body>

Hello

   </body>

</html>



 </source>