【问题标题】:How to select a "word" from a string on click event如何在单击事件中从字符串中选择“单词”
【发布时间】:2020-11-16 20:26:38
【问题描述】:

我有一个字符串,当我单击字符串中的任何单词时,它应该从该单击的单词开始返回另一个字符串,然后返回到字符串的开头,即

str = '这是一个测试字符串。' 点击"test"字后,新的字符串应该是'this is a test'

目前,当我选择整个单词时,它会给出预期的结果,但不是“点击”

此外,在以下链接中,他们提供了解决方案,但它在 jquery 中,我想在 Aguar 10

中实现

Get a word by single click

app.component.html

<textarea class="form-control  rows=10 cols=50 cstm-textarea" (click)="TargetPrefix($event)">
    This is a test string
</textarea>

app.component.ts

TargetPrefix(event) {

    const start = event.target.selectionStart;
    const end = event.target.selectionEnd;
    const result = event.target.value.substr(end - start, start);

    console.log("the clicked word in the string", result);

}

[在此处输入图片描述][1] [在此处输入图片描述][2]

谢谢

点击 [1]:https://i.stack.imgur.com/qjwKO.jpg

选择 [2]:https://i.stack.imgur.com/SG6zT.jpg

【问题讨论】:

  • 告诉我你是如何让它工作的
  • 感谢您的回复。我插入图片,希望你能理解。否则我会尝试解释更多。

标签: angular


【解决方案1】:

这里有一个如何在 Angular 中实现的示例

https://stackblitz.com/edit/angular-ivy-prcewk?file=src%2Fapp%2Fapp.component.ts

我刚刚更新了你的targetPrefix 方法。

【讨论】:

  • 这真是回答某人的好方法!
  • 感谢您的反馈。我检查了链接,但仍然得到刚刚点击的单词,但我想要从点击的单词开始的整个字符串。例如,单击“测试”单词,则结果字符串应为“这是一个测试”,如果单击“是”单词,则它应返回“这是”。目前,在提到的链接中,只有“点击的单词”
  • 这里有另一个例子,在这个例子中,我添加了你正在寻找的内容stackblitz.com/edit/…(我试图使代码足够可读,以便于理解我的方法)
【解决方案2】:

答案已经在您提供的链接中给出。

function TargetPrefix(event) {
  let s = window.getSelection();
  let start = event.target.selectionStart; // save cursor position

  s.modify('extend', 'backward', 'word');
  let b = s.toString();

  s.modify('extend', 'forward', 'word');
  let a = s.toString();

  console.log("the clicked word in the string", b + a);

  s.removeAllRanges();  //clear selection
  document.getElementsByTagName('textarea')[0].selectionStart = start; // restore cursor
}

【讨论】:

  • 感谢@EvgenyV 的回复,但我想在Angular10 中而不是在js 中实现
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多