我有一些文本会传递到页面。使用此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.loging index
。
数据库中的特殊词是:Hello
,Lorem
和dolor
。并不是说它应该有帮助,但是我已经包含了它。
答案 0 :(得分:2)
我不确定我是否正确理解您...由于您已经听过每个click
元素的a.clickable
事件,因此我认为您的问题是检索< / em>部分以获取word
?
在event
句柄中,当前元素作为event
添加到target
对象。要检索html / text内容,可以将此元素与textContent
/ innerText
/ innerHTML
属性结合使用:
viewAnnotation(e) {
const word = e.target.textContent.trim()
// Do something with `word`
}