在本教程中,我将解释jQuery中的.prepend()方法。
jQuery prepend()方法用于将指定的内容插入所选元素的开头。 它是jQuery中的内置方法。
如果我们想在所选元素的末尾插入内容,那么我们想使用jQuery .append()方法。
语法:
1 |
$(selector).prepend(content,function(index,html)); |
JQUERY PREPEND()方法的参数
此.prepend()方法接受两个参数,
内容
这是必需的参数,用于指定需要插入的内容。 要插入的可能值为:
- DOM元素
HTML元素
jQuery对象
文本
FUNCTION( INDEX, HTML)
它是一个可选参数。 它用于指定一个函数,该函数返回插入的内容。
- index –指示元素在集合中的索引位置。
html –指示所选元素的当前HTML。
EXAMPLE 1
1 2 3 4 5 6 7 8 9 |
<pre class="wp-block-syntaxhighlighter-code"><html> <head> <title>Jquery</title> <a href="https://code.jquery.com/jquery-3.4.1.min.js">https://code.jquery.com/jquery-3.4.1.min.js</a> </head> <body> <h1> Everybody, what's up!</h1> </body> </html></pre> |
运行 显示:
Everybody, what’s up!
现在,我将使用jQuery .prepend()方法在“Everybody, what’s up!!”开头插入“ Hello”一词。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<pre class="wp-block-syntaxhighlighter-code"><html> <head> <title>Jquery</title> <a href="https://code.jquery.com/jquery-3.4.1.min.js">https://code.jquery.com/jquery-3.4.1.min.js</a> </head> <body> <h1> Everybody, what's up!</h1> <script type="text/javascript"> $(document).ready(function(){ $("h1").prepend("Hello "); }); </script> </body> </html></pre> |
输出:Hello,Everybody, what’s up!
EXAMPLE 2
1 2 3 4 5 6 7 8 9 |
<pre class="wp-block-syntaxhighlighter-code"><html> <head> <title>Jquery</title> <a href="https://code.jquery.com/jquery-3.4.1.min.js">https://code.jquery.com/jquery-3.4.1.min.js</a> </head> <body> <p>I'm just a paragraph</p> </body> </html></pre> |
输出:I’m just a paragraph
现在,我想在段落标记之前插入粗体标记,我们该如何做,请参见下文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<pre class="wp-block-syntaxhighlighter-code"><html> <head> <title>Jquery</title> <a href="https://code.jquery.com/jquery-3.4.1.min.js">https://code.jquery.com/jquery-3.4.1.min.js</a> </head> <body> <p>I'm just a paragraph</p> <script type="text/javascript"> $(document).ready(function(){ $("p").prepend("<b>I'm bold inserted before paragraph : </b>"); }); </script> </body> </html></pre> |
然后输出:I’m bold inserted before paragraph :I’m just a paragraph
原文:https://developersinspired.com/2020/02/12/jquery-prepend-with-example/