Javascript onClick 函数 - 将文本复制到输入值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18092188/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:42:35  来源:igfitidea点击:

Javascript onClick function - copy text to input value

javascripttextonclick

提问by DevWL

Guys can you help me in creating simple function in JavaScript? I need to change value displayed in a form value. For example

伙计们,你能帮我在 JavaScript 中创建简单的函数吗?我需要更改表单值中显示的值。例如

<span id="copy" onClick="addValue()">**Text1**</span>
<span id="copy" onClick="addValue()">Text2</span>

Based from what I click I want to move it to the input value like this:

根据我点击的内容,我想将其移动到输入值,如下所示:

<input id="paste" class="text" type="input" name="select" value="**Text1**"/>

How will my function have to look like ???

我的功能将如何看起来像???

<script language="javascript" type="text/javascript">   
    <!--Hide Javascript         
      function addValue(){
         document.getElementById('paste').value = this.innerText;       
     }  
 -->  </script>

When I click on Text1in value fild I get "undefined" instead of "Text1" ...

当我单击value fild 中的Text1 时,我得到“未定义”而不是“ Text1”...

回答by EZLearner

I'd use:

我会用:

 function addValue(el) {
     document.getElementById('paste').value = el.innerText || el.textContent || el.outerText;
 }

And set the HTML tag like so:

并像这样设置 HTML 标签:

 <span id="copy" onClick="addValue(this)">**Text1**</span>

回答by Jacob Squires

Give this a go.

试试这个。

You need to pass the element into your function so you can access it's properties to assign them to your form input.

您需要将元素传递到您的函数中,以便您可以访问它的属性以将它们分配给您的表单输入。

HTML:

HTML:

<form name="myForm">
    <span onclick="copyText(this)" >Text1</span>, <span onclick="copyText(this)" >Text2</span>
    <br>
    <input name="myField"></input>
</form>

Javascript:

Javascript:

function copyText(element) {
   document.myForm.myField.value = element.innerHTML;
}

回答by dkellner

document.myForm.myField.value = "I'm a different value now!";

Is this what you're looking for?

这是你要找的吗?

Form and input should have a "name" property, like:

表单和输入应该有一个“名称”属性,比如:

<form name="myForm">
    <input name="myField" />

in the case above.

在上述情况下。