我有用户输入的文本,需要拆分为表格单元格
onclick
。
例如。对于表格单元格中的句子“五个拳击向导快速跳跃”,我可以单击“拳击”一词,文本将分成两个单元格,一个单元格中包含“五人”,另一个单元格中包含“拳击向导快速跳跃”细胞。
这是我现在的代码: (拆分为数组,添加具有唯一 id/索引的范围,并写入innerHTML。单击某个单词时,它会记录特定单词/范围的索引/id)
function pageText() {
let pageText = "The five boxing wizards jump quickly";
pageTextSection.innerHTML = "";
let textArray = pageText.split(" ");
textArray.forEach((item, index) => {
let line = ` <span class='sectionBreakSpan' id='${index}' onclick='splitSection(this.id)' >${item}</span> `;
pageTextSection.innerHTML += line;
})
}
function splitSection(index) {
let arr = pageTwoTextSection.innerText.split(" ")
console.log(index)
}
<table>
<tr class="pageTextRow">
<td>
<p id="pageTextSection"></p>
</td>
</tr>
</table>
当前记录单击单词的索引号。第一个单词是 0,第二个单词是 1...但我需要在单击的单词上 split 并移动到新的表格单元格。如果我单击索引为 3 的单词,则 3 及以上的单词应该位于下一个单元格中。
我更改了一些分割文本的逻辑。
希望对你有帮助。
const text = `The five boxing wizards jump quickly`;
const arrayText = text.split(` `);
const pageText = document.getElementById(`pageText`);
arrayText.forEach((txt, index) => {
pageText.insertAdjacentHTML(
`beforeend`,
`<span id=` + index + `>` + txt + `</span> `
);
});
pageText.addEventListener("click", function (e) {
document.getElementById(`text_1`).textContent = arrayText
.slice(0, e.target.id)
.join(" ");
document.getElementById(`text_2`).textContent = arrayText
.slice(e.target.id, arrayText.length)
.join(" ");
});
<div style="cursor: pointer" id="pageText"></div>
<table>
<tr>
<td id="text_1"></td>
</tr>
<tr>
<td id="text_2"></td>
</tr>
</table>