我有以下解决方案,将点击的字词添加到<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);
}
}());
答案 0 :(得分:0)
我会这样做
(function() {
"use strict";
var input = document.getElementById('display');
var paragraph = document.getElementById('target_para');
paragraph.innerHTML = paragraph.innerHTML.replace(/([^\ ]+)/g, "<span>$1</span>");
paragraph.addEventListener('click', function(e) {
if ('span' !== e.target.nodeName.toLowerCase()) {
return false;
}
input.value += ' ' + e.target.innerHTML;
}, false);
})();
这是一个小提琴:http://jsfiddle.net/HAxCw/
作为输入的单词分隔符,我使用了空格,但您可以将其更改为您想要的任何内容。这是这行代码
input.value += ' ' + e.target.innerHTML;