简体   繁体   English

jQuery:在元素的HTML之前追加项目

[英]JQuery: append item before element's HTML

I need to append some HTML before the existing HTML of an element. 我需要在元素的现有HTML之前附加一些HTML。 I have tried: 我努力了:

$("p").each(function(index){
  $(this).prepend('HELLO! ');
});

But this places it before <p> . 但这会将其放在<p>之前。

I've also tried: 我也尝试过:

$(this).html().prepend('HELLO! ');

The result I need to get would look like: 我需要得到的结果如下所示:

<p>HELLO! This is existing text</p>

Would anyone know the best way to do this? 有人知道这样做的最好方法吗?

You can use .html( function ) to update the innerHTML of all the <p> elements. 您可以使用.html( function )更新所有<p>元素的innerHTML

$('p').html(function(i, old) {
    return 'HELLO! ' + old;
});

 $('p').html(function(i, old) { return 'HELLO! ' + old; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>World!</p> <p>TJ</p> 

If all the <p> elements just contains normal text and not HTML, .text( function ) can also be used instead of .html() . 如果所有<p>元素仅包含普通文本而不是HTML,则也可以使用.text( function )代替.html()

 $("p").each(function(index){ $(this).before('HELLO! '); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>paragraph</p> <p>paragraph</p> 

use .before() 使用.before()

Description: Insert content, specified by the parameter, before each element in the set of matched elements. 说明:将参数指定的内容插入到匹配元素集中的每个元素之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM