结合Javascript中的字符串

时间:2018-08-25 16:02:41

标签: javascript

我正在尝试使用Javascript,我创建了一个简单的HTML页面,其中包含两个字段,一个按钮,另一个应该是前两个字段的组合的字段。

但是,我的Javascript无法正常工作。这是我的文件:

<!DOCTYPE html>
<html>
<head>
  <script src="script.js"></script>
</head>
<body>
  <h2>My First Web Page</h2>
  <p id="first">My First Paragraph.</p>
  <p id="second">My Second Paragraph.</p>
  <input onclick="myFunction()" type="submit" value="Combine" />
  <p id="third">Concatenate first and second.</p>
</body>
</html>

和Javascript

myFunction(){
  var first = document.getElementById("first").value;
  var second = document.getElementById("second").value;

  var third = first + " " + second;
  document.getElementById("third").value = third;

}

或者,我正在this Codepen模板上对其进行测试

4 个答案:

答案 0 :(得分:2)

使用innerText代替value。并正确声明功能。

function myFunction() {
  var first = document.getElementById("first").innerText;
  var second = document.getElementById("second").innerText;
  var third = first + " " + second;
  document.getElementById("third").innerText = third;
}
<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
</head>

<body>
  <h2>My First Web Page</h2>
  <p id="first">My First Paragraph.</p>
  <p id="second">My Second Paragraph.</p>
  <input onclick="myFunction()" type="submit" value="Combine" />
  <p id="third">Concatenate first and second.</p>
</body>

</html>

答案 1 :(得分:2)

您必须将其声明为函数。值不是修改的正确属性,但是您可以使用“ innerHTML”或示例。这是更新的,有效的JS。

function myFunction(){
    var first = document.getElementById("first").innerHTML;
    var second = document.getElementById("second").innerHTML;
    var third = first + " " + second;
    document.getElementById("third").innerHTML = third;
}

答案 2 :(得分:1)

您可以改用textContent

function myFunction(){
  var first = document.getElementById("first").textContent;
  var second = document.getElementById("second").textContent;

  var third = first + " " + second;
  document.getElementById("third").textContent = third;

}

答案 3 :(得分:1)

这里的问题是您要设置段落的值而不是html。

您应该做的是使用innerHTML而不是值。

Here is a stackoverflow discussion about the difference between value and innerHTML: