javascript-在表格单元格中选择文本,然后自动填充同一行中的输入 [英] javascript - select text in table cell and autofill the input on the same row

查看:136
本文介绍了javascript-在表格单元格中选择文本,然后自动填充同一行中的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用document.onmouseup事件选择文本.但是我只能在代码中指定一个输入.如何选择第一行中的文本并将其放在第一行的输入中,然后对第二行做同样的事情?

Right now I'm using document.onmouseup event to select the text. But I'm only able to specify one input in my code. How do I select the text in the first row and put it in the input in the first row, and do the same thing for the second row?

代码段在此处(来自有关文本突出显示事件?):

The code snippet is here (from On Text Highlight Event?):

var t = '';
function gText(e) {
t = (document.all) ? document.selection.createRange().text : document.getSelection();

document.getElementById('input1').value = t;
}

document.onmouseup = gText;
if (!document.all) document.captureEvents(Event.MOUSEUP);

https://jsfiddle.net/nrdq71pz/1/

推荐答案

我从您可以在inputs上需要此功能的地方添加一个通用类.同样,您必须将mouseup事件附加到所有输入.请参阅下面的解决方案.

You can add a common class to the inputs where you want this feature. Also, you have to attach mouseup event to all the inputs. Please see below solution.

var els = document.getElementsByClassName('selection');
function getSelection(textComponent) {
  var selectedText;
  if (textComponent.selectionStart !== undefined) { // Standards Compliant Version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  } else if (document.selection !== undefined) { // IE Version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }
  return selectedText;
}

for (var i = 0; i < els.length; i++) {
  els[i].addEventListener('mouseup', function() {
    this.value = getSelection(this);
  })
}

<table>
  <tr>
    <td>Test code 1</td>
    <td>
      <input type='text' id='input1' class="selection" />
    </td>
  </tr>
  <tr>
    <td>Test code 2</td>
    <td>
      <input type='text' id='input2' class="selection" />
    </td>
  </tr>
</table>

这篇关于javascript-在表格单元格中选择文本,然后自动填充同一行中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆