如何使用javascript从句子中选择单词



假设我在点击试图突出显示该单词的任何单词时,看到一个完整的句子,并将该值读取到javascript变量中。

如果我点击这三个单词,那么这三个词都应该用绿色突出显示,并将值作为字符串存储在变量中。

<p onclick="handleClicks()" class="word" >
Select the choice words that make up the complete sentence.
</p>

现在,如果我单击Selectwordscomplete,那么它应该高亮显示,并且所有选定的值都应该保存在javascript中的一个变量中。

使用javascript可以做到这一点吗?

我试过的是

const handlClicks = (event) => {
const clickedElem = event.target
clickedElem.classList.toggle('active');
}

但这并不奏效。我应该在p标签中使用多个跨度标签,然后对所有跨度应用一个函数吗

您可以动态添加单词,因为它们被封装在span元素中。

然后通过迭代添加逻辑。例如:

const sentence = 'Select the choice words that make up the complete sentence.';
const words = sentence.split(' ');
document.getElementById('content').innerHTML = words.reduce((acc, word) => {
return `${acc} <span class="word">${word}</span>`;
}, '');
const elements = document.getElementsByClassName('word');
[...elements].forEach((element) => {
element.addEventListener('click', () => {
element.classList.toggle('selected');
})
});
.word {
cursor: pointer;
}
.selected {
background-color: palegreen;
}
<div id="content"></div>

如果您想选择单词的接近搜索输入,可以尝试一下。

function func(){
_func();
var search = document.getElementById('search');
var demo = document.getElementById('demo');
var bring = demo.innerHTML;
var bloototh = bring.indexOf(search.value);
if (bloototh >= 0) { 
bring = bring.substring(0,bloototh) + "<span id='index' class='style'>" + bring.substring(bloototh,bloototh+search.value.length) + "</span>" + bring.substring(bloototh + search.value.length);
demo.innerHTML = bring;
}
}

function _func(){
var index = document.getElementById('index');
if(index !== null){
index.outerHTML = index.innerHTML;
}
}
input{
padding: 10px;
margin: 10px;
}
.style {
color: white;
background: gray;
}
<input type="text" id="search"><br>
<input onclick="func();" value="Show" type="button">
<p id="demo">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>

最新更新