[英]Javascript - Highlight specific text inside a string using onClick function
So let's say that we have a HTML paragraph with some text: 假设我们有一个包含一些文本的HTML段落:
<p>Hello. This is a random paragraph with some not so random text inside of this paragraph</p>
And we have an array of strings: 我们有一个字符串数组:
const highlightThisWords = ['random', 'paragraph', 'inside']
What I need is function that will highlight (change the style) of the text inside of the paragraph that is included inside of the array. 我需要的功能是突出显示(更改样式)数组内包含的段落内的文本。 Note the word paragraph is twice inside of the tag but i would need to highlight only the specific one that i clicked on. 请注意,“段落”一词在标记内两次,但是我只需要突出显示我单击的特定段落即可。 Also I need to do some computation after the click like increment a counter. 单击后,我还需要做一些计算,例如增加计数器。
Enviroment: React.js without jquery possible 环境:没有jQuery的React.js可能
You can either create a custom component and use that custom component for split words with " ", I did however tried to create a jsfiddle which isn't very clean, but shows a demo on how it'd work. 您可以创建一个自定义组件,然后将该自定义组件用于带有“”的拆分词,但是我确实尝试创建了一个不是很干净的jsfiddle ,但演示了其工作原理的演示。 To show the code on this post: 要显示此帖子上的代码:
class Hello extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
split(str) {
return str.split(" ");
}
make(str, i) {
return <span key={i} style={{marginLeft:3}} onClick={this.handleClick}>{str}</span>;
}
handleClick(e) {
console.log(this.props.highlights, e.target.innerText);
if (this.props.highlights.indexOf(e.target.innerText) !== -1) {
e.target.style.background = "red";
}
}
render() {
const parts = this.split(this.props.name);
return <div>{parts.map((d, i) => {
return this.make(d, i);
})}</div>;
}
}
ReactDOM.render(
<Hello highlights={['random', 'paragraph', 'inside']} name="This is a random paragraph with some not so random text inside of this paragraph" />,
document.getElementById('container')
);
const highlightThisWords = ['random', 'paragraph', 'inside']; const pNode = document.querySelector('p'); // turn pNode into a highlight-aware DOM pNode.innerHTML = pNode.textContent.split(' ').map(word => { return highlightThisWords.includes(word) ? `<span>${word}</span>` : word; }).join(' '); const potentialHighlights = pNode.querySelectorAll('span'); potentialHighlights.forEach(highlightableWord => { highlightableWord.addEventListener('click', function(e) { // dehighlight all the rest pNode.querySelectorAll('.highlighted').forEach(highlighted => { highlighted.classList.remove('highlighted') }); // highlight the clicked word highlightableWord.classList.add('highlighted'); }); });
.highlighted { color: red; }
<p>Hello. This is a random paragraph with some not so random text inside of this paragraph</p>
Above you find a sample snippet in vanilla js, implementing a minimal solution to your question. 在上方,您可以找到Vanilla js中的样本片段,为您的问题实施了一个最小的解决方案。 There is no human-sane way of determining which exact word was clicked in the paragraph, unless you wrap that word in an html tag of its own. 除非您将单词包装在自己的html标记中,否则没有人为的判断段落中哪个确切单词的方法。 The proposed answers so far are wrapping every single word into a tag. 到目前为止,提出的答案是将每个单词都包装到一个标签中。 While this works, it would not perform great if you have long paragraphs (imagine thousands of DOM nodes in your memory just for a paragraph element). 尽管这行得通,但是如果您有较长的段落(在存储器中仅为一个段落元素想象成千上万个DOM节点),它的性能将不佳。 What I propose is to wrap only "potentially highlightable" words in tags. 我建议的是在标签中只包装“可能突出显示”的单词。
Since you are using React, you can use String.prototype.split()
to split the whole text into array of individual words, and then use conditional rendering to render them as highlighted or not: 由于使用的是React,因此可以使用String.prototype.split()
将整个文本拆分为单个单词的数组,然后使用条件渲染将其渲染为高亮或不高亮:
class MyComponent extends React.Component {
render() {
const arrayOfStrings = stringContainingParagraph.split(' ');
return (
<div>
{arrayOfStrings.map((elem) => (
( highlightThisWords.indexOf(elem) !== -1 ) ?
<mark>{elem}</mark> :
<span>{elem}</span>
))}
</div>
);
}
}
You can then customize this code as you wish ( increment a counter, or using onClick
s to get your desired functionality ). 然后,您可以根据需要自定义此代码(增加计数器,或使用onClick
获得所需的功能)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.