【问题标题】:Javascript function: how to reference the element that calls the function - and extract that element's valueJavascript 函数:如何引用调用该函数的元素 - 并提取该元素的值
【发布时间】:2019-11-18 09:59:43
【问题描述】:

我正在尝试为每一行制作一个带有按钮的表格,我希望每个按钮都将按钮本身的值复制并粘贴到所需的字段中。 我的问题是我没有让 texttocopy 成为 <input button value="">

copypaste(id) {
   var texttocopy = document.getElementById(this);
   var wheretocopy = document.getElementById(id);
   wheretocopy.value = texttocopy.value;
}

我已经尝试了其他一些变体,但查找语法没有结果。

function copypaste(id) {
   var texttocopy = this;
   var wheretocopy = document.getElementById(id);
   wheretocopy.value = texttocopy.value;
}

texttocopy 是调用函数的值。

html 在 php 中,所以这就是 .连接器和 " 和 ' 的切换。

按钮在哪里: php echo '<input TYPE="BUTTON" id="barcodebutton" value ="'.$row['barcode1'].'" onclick="copypaste('."'primaryRFID'".');">'

输入数据的字段: html <INPUT TYPE="TEXT" id="primaryRFID" NAME="primaryRFID">

预期的结果是primaryRFID的输入变成按下按钮的值。

【问题讨论】:

    标签: javascript function getelementbyid this-keyword


    【解决方案1】:

    当您从 onclick 属性内部调用函数时,该函数在没有任何 this 绑定的情况下被调用。但是,this 在执行 onclick 代码本身时被绑定,因此您可以将其作为常规参数传递:

    onclick="copypaste(this, '."'primaryRFID'".');"
    

    所以现在通过函数参数获取该参数值:

    function copypaste(texttocopy, id) {
       var wheretocopy = document.getElementById(id);
       wheretocopy.value = texttocopy.value;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 2015-11-09
      • 2014-02-26
      • 1970-01-01
      相关资源
      最近更新 更多