在 JavaScript 代码中的变量后添加文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9055945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:27:19  来源:igfitidea点击:

Adding text after variable in JavaScript code

javascriptjqueryvariables

提问by UserIsCorrupt

var example = "Test" ;

$('button').click(function() {
 $('div').append(example);
});

<button>Whatever</button>
<div></div>

How can I add text after the variable examplein the jQuery code?

如何example在 jQuery 代码中的变量后添加文本?

In other words, in the jQuery code how can I add text (in this example: "blah") after the variable so the HTML code will appear like this

换句话说,在 jQuery 代码中,如何在变量后添加文本(在本例中:“blah”),以便 HTML 代码显示如下

<div>Testblah</div>

回答by Selvakumar Arumugam

Not sure if this is what you are looking for,

不确定这是否是您要找的,

$('div').html(example + "blah");

Note I have used .htmlinstead of .append. You can also use .textif you gonna insert plain text inside the div.

注意我使用了.html而不是 .append。如果要在 div 中插入纯文本,也可以使用.text

Above is just a plain javascript string concatenation. You should read about String Operators

上面只是一个简单的 javascript 字符串连接。您应该阅读有关字符串运算符的信息

Also the above doesn't change the value of var example. If you want the value to be changed then assign the result to the example and set the div html.

此外,上述内容不会改变 var 示例的值。如果您希望更改值,则将结果分配给示例并设置 div html。

 example += 'blah';
 $('div').html(example);

回答by user1175575

change to this :

更改为:

var example = "Test" ;
$('button').click(function() {
  example=example+'blah';
 $('div').append(example);
});

or:

或者:

var example = "Test" ;
var exp="blah";
$('button').click(function() {
  example=example+exp;
 $('div').append(example);
});

回答by Iamcoolcoder

Try using concat (Vanilla JS):

尝试使用 concat (Vanilla JS):

var example = "Test"
//to concatenate:
example = example.concat("blah")
document.write(example)
//if you want a space:
example = example.concat(" blah")
document.write(example)

回答by Mahmoud Gamal

Just like this:

像这样:

$('button').click(function() {
    $('div').append(example + "blah");
});

回答by Mike

You will have to name your div like this:

您必须像这样命名您的 div:

<div id="one"> </div>

and put the jQuery code like this

并像这样放置 jQuery 代码

$('#one').html(example);

回答by Matías Fidemraizer

Maybe I misunderstood your question, but is this a simple string concatenation?

也许我误解了你的问题,但这是一个简单的字符串连接吗?

var example = "Test";

$('button').click(function() {
 example += "blah"; // ????
 $('div').append(example);
});