首页 > 解决方案 > 如何在单击事件中从字符串中选择“单词”

问题描述

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

str = '这是一个测试字符串。' 单击“测试”一词后,新字符串应类似于“这是一个测试”等。

目前,当我选择整个单词时,它会给出预期的结果,但不会在 'click' 上给出。

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

一键获取单词

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]

谢谢

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

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

标签: angular

解决方案


在这里,您有一个如何以角度实现它的示例

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

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


推荐阅读