我正在寻找一种方法,在页面上点击字符串时,将特定字词添加到字符串中。
目前我有一个解决方案,如下所示: http://jsfiddle.net/BvP4n/
目前有两个问题,如果我能得到你的建议改变它们会很棒:
我需要<span>
标签用一个标签覆盖整个文本,但点击时只会将单击的特定单词发送到单词字符串。
我需要将单词放在输入框中作为表单的一部分,而不是<div>
。
答案 0 :(得分:1)
DEMO http://jsfiddle.net/BvP4n/7/
target
选择器以获取这些项目<div/>
,而不是将文字值附加到<input/>
<p id="target_para">
Here's an example of the thing you wanted to be made clickable.
</p>
<input type="text" id="display" />
(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);
}
}());
答案 1 :(得分:0)
1)使用搜索选项:
Detect which word has been clicked on within a text
2)非常简单的代码更改:只需添加<input type="text" id="test"/>
并在updateList方法中添加:document.getElementById("test").value = words.join(", ");
,请参阅此处:http://jsfiddle.net/BvP4n/