【问题标题】:How do I select the last character of a string, using JavaScript?如何使用 JavaScript 选择字符串的最后一个字符?
【发布时间】:2021-01-19 16:21:04
【问题描述】:

我有一个函数可以获取用户在input 中键入的字符串的最后一个字符。但是如何使用execCommand() 选择那个单个字符?目标是将其复制到不同的input

我试过element.select(),但没有结果。

要粘贴到新input 中的字符必须是原始输入中可见的字符,而不是与用户键入的键盘键对应的字符,因为这一切的原因是有一个外部 JS 库处理一些一个input中的CJK字符转换,并将结果移动到另一个..

我将采用复制粘贴的方法。因此,需要选择角色。但如果有更好的方法来实现它,请随时告诉我。

我对 Vanilla JavaScript 和 jQuery 方法持开放态度。

这是我的代码:

JSFiddle

function copyPaste () {
  var i1 = document.getElementById('userInput');
  var i2 = document.getElementById('input2');
  var c = i1.value.substr(lol.length - 1);
  c.select();
  document.execCommand('copy');
  i2.focus();
  document.execCommand('paste');
  i1.focus();
}
input {
  width: 255px;
}
  
button {
  display: block;
  margin: 20px 0;
  text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">

<button type="button" onclick="copyPaste"();>Then, click here to copy the last character<br>of the above input into the next input.</button>

<input type="text" id="input2" value="Some text...">

【问题讨论】:

  • 为什么要使用剪贴板?为什么不直接从第一个输入中读取值,并使用它将最后一个字符放在第二个输入中呢?此外,execCommand 是一个过时的功能......
  • 现在粘贴是not supported
  • @trincot 我该怎么做?
  • 我将其发布为答案。

标签: javascript select cjk execcommand


【解决方案1】:

您不应使用execCommand,因为它已过时。此外,您不需要使用剪贴板将(部分)字符串传输到另一个输入框。这可以通过标准字符串处理来完成:

  • 您可以使用slice(-1) 来获取最终字符。

  • 我也更喜欢addEventListener 而不是onclick 属性(您也有错字)。

  • 使用+=,您可以附加提取的字符:

var input = document.getElementById('userInput');
var output = document.getElementById('input2');
var btn = document.querySelector('button');

btn.addEventListener("click", function () {
  output.value += input.value.slice(-1);
});
input {
  width: 255px;
}
  
button {
  display: block;
  margin: 20px 0;
  text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">

<button type="button">Then, click here</button>

<input type="text" id="input2" value="Some text...">

【讨论】:

  • 非常感谢您的帮助!这样做确实更有意义。
【解决方案2】:

以下内容对我有用:

html:

<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button" onclick="copyPaste()";>Then, click here to copy the last character<br>of the above input into the next input.</button>
<input type="text" id="input2" value="Some text...">

js:

function copyPaste () {
  var i1 = document.getElementById('userInput');
  var i2 = document.getElementById('input2');
  var c = i1.value.slice(i1.value.length - 1);
  i2.value = c;
}

使用slice() 获取字符串的最后一个字符。请注意,我还在您的 html 中修复了 onclick 处理程序。

【讨论】:

  • 这种方法的问题是它替换了第二个input中已经存在的所有内容。我需要保持它以前的值。
猜你喜欢
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
相关资源
最近更新 更多