0

我有以下解决方案,可将点击的单词添加到<input>字段字符串中。

但是,我想更改 javascript 以允许我:

  1. 保留我手动添加到<input>字段中的文本。目前它被覆盖。
  2. <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);
    }
}());
4

1 回答 1

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;
于 2013-10-16T14:32:34.330 回答