Change content of div - jQuery

后端 未结 6 2132
天命终不由人
天命终不由人 2020-11-29 02:22

How is it possible to change the content of this div, when one of the LINKS is clicked?


      
6条回答
  •  青春惊慌失措
    2020-11-29 02:58

    There are 2 jQuery functions that you'll want to use here.

    1) click. This will take an anonymous function as it's sole parameter, and will execute it when the element is clicked.

    2) html. This will take an html string as it's sole parameter, and will replace the contents of your element with the html provided.

    So, in your case, you'll want to do the following:

    $('#content-container a').click(function(e){
        $(this).parent().html('I\'m a new link');
        e.preventDefault();
    });
    

    If you only want to add content to your div, rather than replacing everything in it, you should use append:

    $('#content-container a').click(function(e){
        $(this).parent().append('I\'m a new link');
        e.preventDefault();
    });
    

    If you want the new added links to also add new content when clicked, you should use event delegation:

    $('#content-container').on('click', 'a', function(e){
        $(this).parent().append('I\'m a new link');
        e.preventDefault();
    });
    

提交回复
热议问题