JavaScript 字符串连接不起作用

JavaScript string concatenation not working

本文关键字:不起作用 连接 字符串 JavaScript      更新时间:2023-09-26

这个用于连接的javascript代码不起作用。 我在关闭脚本标签之前尝试了警报,它会显示,但下面的代码我想在第三个或不同的文本字段中显示结果。

.HTML:

<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>

JavaScript:

var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;
function concate()
{
    st=s+t;
    document.getElementById("str3").value.innerHTML=st;
    console.log(st);
    document.write(st); 
}

没有函数.value.innerHTML应该是:

document.getElementById("str3").value = st;

此外,您应该获取函数内的字段值并使用}关闭函数定义,检查下面的示例。

希望这有帮助。


function concate()
{
     var s=document.getElementById("field").value;
     var t=document.getElementById("str2").value;
     document.getElementById("str3").value=s+t;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>

function concate() {
    var s=document.getElementById("field").value;
    var t=document.getElementById("str2").value;
    var st=document.getElementById("str3").value;
    // this is a standard way to concatenate string in javascript
    var result = s+t;
    document.getElementById("str3").value=result;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3" readonly><br>
<button onclick="concate()">Concatenate</button>