我有传递到页面的文本。还有一些"特殊单词"通过使用highlight function below
来突出显示。
它将它放入一个<a>
标记中,其中包含它的类和使它突出显示的样式。运行此功能后,特殊单词将在文本中突出显示并可单击。
因此,它将对文本执行此操作:<a class="clickable" style="background-color: yellow;">Hello</a>
。创建一个<a>
,将其放入class
和styles
中。
我现在遇到的问题是,当我单击一个突出显示的单词,并且该单词有自己的class='clickable'
时,我如何获取被单击的单词?我需要检查点击了哪个单词,以便查询数据库并获取该单词的注释。
highlight = words => {
const high = document.getElementById('scrollable');
const paragraph = high.innerHTML.split(' ');
const res = [];
paragraph.map(word => {
let t = word;
if (words.indexOf(word) > -1) {
t =
'<a class="clickable" style="background-color: yellow;">' +
word +
'</a>';
console.log(words.indexOf(word));
}
// console.log(words);
res.push(t);
});
high.innerHTML = res.join(' ');
const elementsToMakeClickable = document.getElementsByClassName(
'clickable'
);
const elementsToMakeClickableArray = Array.from(elementsToMakeClickable);
elementsToMakeClickableArray.map(element => {
element.addEventListener('click', this.viewAnnotation.bind(this));
});
}
要保存一些时间日志:console.log(words);
将返回这三个特殊单词。console.log(words.indexOf(word));
将以0,1或2的形式返回每个单词,因为显然我们是console.logindex
。
数据库中的特殊词有:Hello
、Lorem
和dolor
。不是说它应该有帮助,但我已经把它包括在内了。
我不确定我是否正确理解你。。。由于您已经为每个a.clickable
-元素监听了click
-事件,我认为您的问题是获取word
的检索部分?
在event
-hander中,当前元素被添加到event
-对象中作为target
。要检索html/文本内容,可以将此元素与textContent
/innerText
/innerHTML
属性结合使用:
viewAnnotation(e) {
const word = e.target.textContent.trim()
// Do something with `word`
}