简体   繁体   English

如何将两个变量与 Javascript 结合起来?

[英]How do I combine two variables with Javascript?

I have a form that collects first name and last name via two div elements:我有一个通过两个 div 元素收集名字和姓氏的表单:

<div class="form-row">
  <div class="col">
    <input type="text" class="form-control" id="lastName" placeholder="last name" />
  </div>
</div>

<div class="form-row">
  <div class="col">
    <input type="text" class="form-control" id="firstname" placeholder="first name" />
  </div>
</div>

In the script I have the following line在脚本中,我有以下行

const lastName = document.getElementById('lastName').value;

What I would like to do is produce a constant called fullname which comprises of firstname+lastname我想做的是生成一个名为 fullname 的常量,其中包含 firstname+lastname

How can I rewrite the line starting with const above to do this?如何重写上面以 const 开头的行来做到这一点?

This one should be fairly simply.这个应该相当简单。 You already have a way of extracting the value of the lastName input.您已经有了一种提取lastName输入值的方法。 So just do the same for firstName and then concatenate the two variables.因此,只需对firstName执行相同操作,然后连接两个变量。

const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;

const fullName = `${firstName} ${lastName}`;

Using your existing syntax:使用您现有的语法:

const fullName = document.getElementById('firstname').value + ' ' + document.getElementById('lastName').value;

There are of course other ways to get these values and this assumes there will be a value but you get the gist.当然还有其他方法可以获得这些值,这假设会有一个值,但你明白了要点。

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

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