2016-08-21 29 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

相關問題