2016-08-21 44 views
0

我有一个<ul>标记内的单词列表,我试图在用户单击<li>元素时在文本区域内添加单词。该单词添加正确,但我试图从textarea中删除该单词,如果用户点击相同的<li>元素。jQuery在字符串单击,添加或删除在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

你需要的时候你要删除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>

+0

谢谢你这么多,像现在预期工作。我会仔细研究你的代码,尤其是'val(function()'部分。再次感谢Satpal。 – mlclm