有没有办法将html按钮的内容复制到另一个?

时间:2016-02-04 18:59:32

标签: html button

我正在尝试将html页面中的按钮内容复制到另一个按钮,我尝试了以下代码,它不起作用,它只能将文本从一个输入字段复制到另一个,如何做同样的事情按钮?

<!DOCTYPE html>
<html>
<body>

Field1: <input type=text id=field1 value="Hello World!"><br>
Field2: <input type=text id=field2><br><br>
<button id=BT_1 type=button onclick=myFunction()>ABC</button><br>
<button id=BT_2 type=button onclick=myFunction()>123</button>

<P>
<button onclick="myFunction()">Copy Text</button>

<script>
function myFunction()
{
  document.getElementById("BT_2").value = document.getElementById("BT_1").value;
  document.getElementById("BT_2").value = document.getElementById("field1").value;
  document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>

</body>
</html>

喜欢以下内容:

<button id=BT_1 type=button onclick=myFunction(BT_1)>ABC</button>

function myFunction(From_BT)
{
  document.getElementById("BT_2").value = document.getElementById(From_BT).value;
}

1 个答案:

答案 0 :(得分:1)

这是你的想法吗? https://jsfiddle.net/jimedelstein/asfh2q2c/4/

按钮的值与innerHTML不同。

另一个解决方案是按原样保留您的javascript,但请使用

<input type="button" value="Button Text" id="BT_1" onclick='myFunction()' ></input> 

请参阅此处查看两者的示例:http://permadi.com/tutorial/jsInnerHTMLDOM/

你也可以创建一个函数,让我们称之为copy_button_text,它接受源按钮和目标按钮两个参数,我们可以这样调用onclick ='copy_button_text(“BT_1”,“BT_2”)'。您将在小提琴中看到myFunction()有效,但每个按钮实际上都使用此功能将其文本应用于另一个按钮。

相关问题