我有以下解决方案,可将点击的单词添加到<input>
字段字符串中。
但是,我想更改 javascript 以允许我:
- 保留我手动添加到
<input>
字段中的文本。目前它被覆盖。 <p>
从转移到的文本中排除句号<input>
HTML
<p id="target_para">
Here's an example of the thing you wanted to be made clickable.
</p>
<input type="text" id="display" />
JS
(function () {
"use strict";
var para, targets, display, words, clickHandler, updateList, i, j, cur;
display = document.getElementById("display");
para = document.getElementById("target_para");
// Wrap every word in a span element
para.innerHTML = '<span>' + para.innerText.replace(/ /g,'</span><span> ') + '</span>';
// Updated target
targets = para.getElementsByTagName("span");
words = [];
// Handler for clicking a clickable element
clickHandler = function () {
var text = this.innerText || this.textContent,
idx = words.indexOf(text);
if (words.indexOf(text) < 0) {
// If not already in list, add it
words.push(text);
} else {
// Otherwise remove it
words.splice(idx, 1);
}
updateList();
};
// Update display of word list
updateList = function () {
while (display.firstChild) {
display.removeChild(display.firstChild);
}
// Set the input box value
display.value = words.join(",");
};
// Bind event handlers to clickable elements
for (i = 0, j = targets.length; i < j; i++) {
cur = targets[i];
cur.addEventListener("click", clickHandler, false);
}
}());