字符串上的jQuery单击,添加或删除textarea中匹配的文本

时间:2016-08-21 13:45:44

标签: javascript jquery html replace textarea

我在<ul>标记内有一个单词列表,当用户点击<li>元素时,我正试图在textarea中添加该单词。这个词被正确添加,但是如果用户点击同一个<li>元素,我正试图从textarea中删除该单词。

   <ul>
       <li>Word One</li>
       <li>Word deux</li>
       <li>Other Word three</li>
       <li>yet another Word 4</li>
   </ul>

   <textarea id="list" rows="4" cols="20"></textarea>

的jQuery

jQuery(document).ready(function() {

// removing the textarea value when window is loaded again
// otherwise for some reason all the values entered before are still there ?

jQuery(window).load(function() {
    jQuery('#list').val('');  
})

jQuery('ul li').click(function(addWord) {

    var choice = jQuery.trim($(this).text());
    var textArea = jQuery("#list");

    // if the <li> with the word was allready clicked, then remove its "selected" class
    if (jQuery(this).hasClass('selected')) {
        jQuery(this).removeClass('selected');

        //textArea.replace(choice,'');

   } else {
       // add class selected to the clicked <li> word, add the word to the textarea
       jQuery(this).addClass('selected');
       textArea.val(textArea.val() + choice + ' , ').text(textArea.val());
   }
});
}

1 个答案:

答案 0 :(得分:3)

删除selected课程时需要替换文本。这里使用.val(function)

jQuery(document).ready(function() {

  jQuery('ul li').click(function(addWord) {

    var choice = jQuery.trim($(this).text());
    var textArea = jQuery("#list");

    // if the <li> with the word was allready clicked, then remove its "selected" class
    if (jQuery(this).hasClass('selected')) {
      jQuery(this).removeClass('selected');

      textArea.val(function(_, val) {
        return val.replace(choice + ' , ', '');
      });
    } else {
      // add class selected to the clicked <li> word, add the word to the textarea
      jQuery(this).addClass('selected');
      textArea.val(function(_, val) {
        return val + choice + ' , ';
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Word One</li>
  <li>Word deux</li>
  <li>Other Word three</li>
  <li>yet another Word 4</li>
</ul>

<textarea id="list" rows="4" cols="20"></textarea>