简体   繁体   English

如何在元素的原始文本之前添加文本

[英]How to add text before of an element's original text

I'm trying to add some text before of the original text of an element. 我正在尝试元素的原始文本 之前添加一些文本。
Now, I know to insert text after the original content, I can do it using createTextNode like the example below: 现在,我知道要在原始内容之后插入文本,可以使用createTextNode如下例所示:

 $("#button").click(function() { $( ".text" ).append( document.createTextNode( " Hello" ) ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <button id="button">Button</button> <div class="text"> Some random text</text> 

But how can I add it before? 但是我该如何添加呢?

.prepend is the function you want. .prepend是您想要的功能。

 $("#button").click(function() { $( ".text" ).prepend( document.createTextNode( " Hello" ) ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <button id="button">Button</button> <div class="text"> Some random text</text> 

You need to use prepend function. 您需要使用前置功能。 Also , no need of createTextNode. 另外,不需要createTextNode。

$("#button").click(function() {
    $( ".text" ).prepend(" Hello");
});

http://jsfiddle.net/8yukxftb/ http://jsfiddle.net/8yukxftb/

Can't you also just alter the text there? 您不能只在那里修改文字吗? It doesn't seem from your example that there is anything wrong with 从您的示例看来,似乎没有任何问题

$( ".text" ).text(function(i,txt){ return "Hello " + txt });

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

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