How to remove an appended element with Jquery and why bind or live is causing elements to repeat

后端 未结 5 1885
眼角桃花
眼角桃花 2020-12-30 05:20

Now I know this basic question has been asked before, but I must be doing something wrong. I know that an appended element must bound before I can do anything to it. However

相关标签:
5条回答
  • 2020-12-30 05:33

    you could use replaceAll instead of remove and append replaceAll

    0 讨论(0)
  • 2020-12-30 05:39

    The live function is registering a click event handler. It'll do so every time you click the object. So if you click it twice, you're assigning two click handlers to the object. You're also assigning a click handler here:

    onclick="feedback('the message html')";
    

    And then that click handler is assigning another click handler via live().

    Really what I think you want to do is this:

    function feedback(message)
    {
        $('#feedback').remove();
    
        $('.answers').append('<div id="feedback">'+message+'</div>');
    }
    

    Ok, per your comment, try taking out the onclick part of the <a> element and instead, putting this in a document.ready() handler.

    $('#answer').live('click',function(){
                         $('#feedback').remove();
                         $('.answers').append('<div id="feedback">'+message+'</div>');
                     });
    
    0 讨论(0)
  • 2020-12-30 05:39

    I would do something like:

    $(documento).on('click', '#answer', function() {
      feedback('hey there');
    });
    
    0 讨论(0)
  • 2020-12-30 05:47

    If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on() to register event handlers. Here's a link to the jQuery docs about on: link

    Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.

    Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.

    $('#answer').on('click', function() {
      feedback('hey there');
    });
    
    var counter = 0;
    
    function feedback(message) {
    
      $('#feedback').remove();
    
      $('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');
    
      counter++;    
    }
    
    0 讨论(0)
  • 2020-12-30 05:57

    Do you have multiple Radio Buttons on the page..

    Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button

    0 讨论(0)
提交回复
热议问题