2013-10-16 32 views
0

我有以下解決方案,將單擊的單詞添加到<input>字段字符串中。將點擊的單詞添加到字符串2

不過,我想改變的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); 
    } 
}()); 
+0

*你嘗試過什麼?* –

+0

我明白,要保持手動輸入到''字段中的文本是什麼,是根本,是基於先前的反饋。 –

+0

排除完全停止是我嘗試使用'g /./'實現的,但沒有成功 –

回答

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;