insertBefore()是jQuery中的内置方法,用于在指定元素之前插入一些HTML内容。 HTML内容将在每次出现指定元素之前插入。
用法:
$(content).insertBefore(target)
这里的内容是需要在指定目标之前插入的HTML内容。
参数:它接受参数“target”,该参数是要在其之前插入内容的目标。
返回类型:它不返回任何值。
代码1:
<!DOCTYPE html> 
<html> 
  
<head> 
    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
    <script> 
        $(document).ready(function() { 
            $("div").click(function() { 
                // insertBefore 
                $("<p>You should follow GeeksForGeeks</p>").insertBefore("p"); 
            }); 
        }); 
    </script> 
</head> 
  
<body> 
  
    <p>To learn jQuery </p> 
  
    <div>Click here to complete</div> 
  
</body> 
  
</html>输出:
在点击div内容之前,
To learn jQuery Click here to complete
点击div内容后,
You should follow GeeksForGeeks To learn jQuery Click here to complete
代码2:
<!DOCTYPE html> 
<html> 
  
<head> 
    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
    <script> 
        $(document).ready(function() { 
            $("div").click(function() { 
                // insertBefore 
                $("<p>You should follow GeeksForGeeks</p>").insertBefore("p"); 
            }); 
        }); 
    </script> 
</head> 
  
<body> 
  
    <p>To learn jQuery </p> 
  
    <p> To learn coding </p> 
  
    <div>Click here to complete</div> 
  
</body> 
  
</html>输出:
在点击div内容之前,
To learn jQuery To learn coding Click here to complete
点击div内容后,
You should follow GeeksForGeeks To learn jQuery You should follow GeeksForGeeks To learn coding Click here to complete
相关用法
- JQuery after()用法及代码示例
- JQuery val()用法及代码示例
- JQuery eq()用法及代码示例
- JQuery one()用法及代码示例
- JQuery first()用法及代码示例
- JQuery last()用法及代码示例
- JQuery has()用法及代码示例
- JQuery on()用法及代码示例
- JQuery scrollLeft()用法及代码示例
- JQuery submit()用法及代码示例
- JQuery children()用法及代码示例
- JQuery select()用法及代码示例
- JQuery serialize()用法及代码示例
- JQuery scrollTop()用法及代码示例
- JQuery resize()用法及代码示例
注:本文由纯净天空筛选整理自ShivamKD大神的英文原创作品 jQuery | insertBefore() with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
