How does JQUERY click insert and then click delete?

<div class="box">
    <div class="text"></div>
    <ul>
        <li>1</li>
        <li>...</li>
        <li>N</li>
    </ul>
</div>
The

HTML structure is shown above, and the effect you want to achieve is that clicking on one of the LI will insert the currently clicked LI with < p class= "li-text" > text

in the form of < div class="text" > < / div > and add a class="cur" to the currently clicked li. You can only click li, up to three times and insert three into the text . The question is, how do you finish inserting after you currently click li, and then click to delete the currently inserted content? Solution, thank you very much! ~

Mar.12,2021

  1. first of all, since jQuery is an imperative library, it is recommended that you list the requirements one by one so that you know what to do at each step and make further optimizations. Then there is:

    1. Click one of the LI
    2. add class='cur' to the currently clicked LI
    3. < p class= "li-text" > text

      insert < div class='text' > < / div >
    4. you can only click li, at most three times to insert three into text
    5. finish inserting after the current click on li, and then click to delete the currently inserted content
  2. here you will find that the description of the subject is very messy, which is generally why the code can not be written. This step is to analyze the requirements sorted out in the previous step:

    1. Click li, must require event listening
    2. use $(this) in the event callback to capture the elements of the current event, not to mention adding class.
    3. Don't say much
    4. is "only 3 clicks per li" or "all li can be clicked 3 times in total"? You can add a data attribute to ul or each li to store the number of times, and then read the number of times each time the event is called back.
    5. join p directly tie a callback $(this). Remove () self-delete

<div class="box">
    <div id="showText" class="text"></div>
    <ul id="liParent">
        <li>1</li>
        <li>...</li>
        <li>N</li>
    </ul>
</div>
$('-sharpliParent').on('click' , 'li' , function(e){ 
   var text = e.target.textContent;
   var p = $('<p class="li-text">'+ text +'

'); p.on('click',function(){ p.remove(); }); $('-sharpshowText').append(p); });

https://codepen.io/randyou/pe.


try to save it in the current li with data () . When you click, you can determine whether there is a corresponding node. If so, remove it, otherwise add

.
Menu