jQuery Prepend和Prependto示例

时间:2020-02-23 14:46:12  来源:igfitidea点击:

在本教程中,我们将看到jQuery prepend和prependto方法。

两者都执行相同的任务,在每个选定元素的内容之前插入文本或者html,因此它将将文本或者html放到第一个所选元素索引。
这两种方法都将文本或者HTML添加为子于所选元素.

Prepend和PrependTo方法的语法不同。

prepend()的语法:

$("selectors").prepend("element to be inserted")

prependto()的语法:

$("element to be inserted") .prependTo("div");

让我们通过示例来理解:

<!doctype>
<html>
<head>
  <title>Jquery prepend and prependTo example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery prepend and prependTo example</h2>
<style>
   .red{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
   }
 .blue{
        border:3px dotted red;
        color:blue;
        font-family: arial narrow;
   }
.blackBorder{
        border:4px dotted black;
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#prependButton").click(function(){
         $("div").prepend("inserting using prepend");
      });
$("#prependToButton").click(function(){
         $("inserting using prependTo").prependTo("div");
      });
$("#reset").click(function(){
         location.reload();
   });
 });
 
</script>
<body>
  <button id="prependButton">Using prepend</button>
  <button id="prependToButton">Using prependTo</button>
<button id="reset">Reset</button>
<div class='blackBorder'>
 Hello world from theitroad!!!!
   </div>
<br
<div class='blackBorder' >
 Welcome to JQuery.
  </div>
</body>
</html>