如何连接 HTML 和 JavaScript 中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4921835/
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
How can I concatenate value in HTML and JavaScript?
提问by gnubala
For example
例如
<input type="text" name="disp">
<input type="button" name="but0" value="0" onclick=""+"calc.disp.value=0"+"">
Here if I click the button 0 means it should display the 0 in text box. If I click the button it should concatenate in that box. But it replaces that is the code is wrong.
在这里,如果我单击按钮 0 意味着它应该在文本框中显示 0。如果我单击按钮,它应该连接在那个框中。但它取代的是代码错误。
回答by Anthony Grist
As far as I understand it, you want each button click to add 0 to the text box contents. So it starts out empty, and when you push the button the first time, the contents changes to 0. Pushing it a second time changes the contents to 00.
据我了解,您希望每次单击按钮将 0 添加到文本框内容中。所以它开始是空的,当你第一次按下按钮时,内容变为 0。第二次按下它会将内容变为 00。
Assuming that's correct, try this:
假设这是正确的,试试这个:
<input type="text" name="disp">
<input type="button" name="but0" value="0" onclick="calc.disp.value=calc.disp.value + '0';">
回答by Luke Duddridge
If you are allowed to use jQueryI would suggest that as the code needed then becomes a lot easier to see what is going on:
如果您被允许使用jQuery,我建议您在需要的代码时更容易看到正在发生的事情:
First add an id attribute to each input.
首先为每个输入添加一个 id 属性。
<input type="text" name="disp" id="textBox">
<input id="button0" type="button" name="but0" value="0">
you want to add 0s? so if you entered 1 then you hit the 0 button it will show 10 then again will change to 100:
你想加0吗?所以如果你输入 1 然后你点击 0 按钮它会显示 10 然后又会变成 100:
<script type="text/ecmascript">
$(document).ready(function()
{
$("#button0").click(function()
{
var textVal = $("#textBox").val();
$("#textBox").val(textVal + 0);
});
});
</script>
回答by vishnu
var sum = document.getElementById("id1").value
+ document.getElementById("id2").value
+ document.getElementById("id3").value;
回答by Ankur
Hi you can do it by following way
您好,您可以通过以下方式进行
<input type="text" name="tst" id="tst">
<input type="button" value="0" onclick="javascript:document.getElementById('tst').value = document.getElementById('tst').value + this.value "

