我正在尝试获取一个文本,并添加一个onclick事件,在文本的每个单词上都有一个函数。它对一些句子非常有效,但对另一些句子则不然。当它不工作时,部分html标记将显示在页面上。我注意到,当我使用"a“或"an”这两个词时,它从来不会起作用,但我不知道为什么。我就是这样做的:
在页面中输入文本
<textarea id="text-input"></textarea>
函数addLink(){ let text = document.getElementById(' text -input').value const word= text.match(/\w+/g) words.forEach(word => { text = text.replace(word,<span onclick=showWordDetail('${word}')>${word}</span>
) }) document.getElementById(‘=>’).innerHTML=text}函数showWordDetail(word){ let wordDetail = document.getElementById('word-detail')结果= <h3>${word}</h3>
返回wordDetail.innerHTML =结果}
<button onclick="addLink()">Submit</button>
例如,如果我输入,“我的兄弟是工程师”。它工作得很完美。onclick事件将添加到所有单词中。
但如果我输入“我的兄弟是一名工程师”,这就是结果:
“onclick=showWordDetail(‘我的’)>我哥哥是个工程师.”
我合并了所有尝试的数组,文本被正确分割。所以我不知道为什么有时起作用,但有时不行。
发布于 2021-06-17 10:21:26
我想这就是你想要的。它避免了一些问题的答案,只是分裂在空间。
const wordDetail = document.getElementById('word-detail'),
input = document.getElementById('text-input'),
result = document.getElementById('result');
function addLink() {
result.innerHTML = input.value.replace(/\w+/g,`<span onclick="showWordDetail('$&')">$&</span>`)
}
function showWordDetail(word) {
wordDetail.innerHTML = `<h3>${word}</h3>`
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<div id="result"></div>
<hr/>
<div id="word-detail"></div>
发布于 2021-06-17 10:16:31
我哥哥是个工程师
这包括an
这个词。
现在看看您用什么替换了My
:
My
那么,当您到达an
时,什么将被替换?
字符an
的第一个位置是什么?
an
of <span>
你可能会更好地做这样的事情:
const html = words.map(word => `<span ....>${word}</span>`).join(" ");
document.getElementById('result').innerHTML = html
在这里,您逐个构建一组新的HTML,而不是一片片地替换旧的内容。
发布于 2021-06-17 10:20:34
相反,使用split(),使用分隔符空格并替换每个单词,替换后,将其添加到文本值中,如下所示:
function addLink(){
let text = document.getElementById('text-input').value;
const words = text.split(" ");
text = "";
words.forEach(word => {
text += word.replace(word, `<span onclick=showWordDetail('${word}')>${word}</span> `);
});
document.getElementById('result').innerHTML = text;
}
function showWordDetail(word){
let wordDetail = document.getElementById('word-detail');
wordDetail.innerHTML = `<h3>${word}</h3>`;
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<p id="result"></p>
<div id="word-detail"></div>
https://stackoverflow.com/questions/68017137
复制相似问题