仅选择添加到 DOM 的单击元素

Selecting only the clicked element that was added to the DOM

我一直在制作这个网络应用来测试一下 JQuery。它只是将元素添加到 DOM。我一直在处理新添加元素的点击事件时遇到问题。我希望能够只更改我单击的那个而不是整组元素。

这里是 link 演示 video

这是我的代码:

    var main = function() {
    $('.btn').prop('disabled', true);

    $('.post-btn').click(function() {
        var text = $('.status-box').val();
        $('<li>').text(text).fadeIn(600).prependTo('.posts');
        $('.status-box').val('');
        $(this).prop('disabled', true);
        $('.counter').text(140);
    });

    $('.status-box').keyup(function() {
        $('.counter').css('color', '#404040');
        var characters = $('.status-box').val().length;
        var charactersleft = 140 - characters;
        $('.counter').text(charactersleft);

        if(charactersleft < 0) {
            $('.post-btn').prop('disabled', true);
            $('.counter').css('color', 'red');
        }

        else if(charactersleft === 140) {
            $('.post-btn').prop('disabled', true);
        }

        else {
            $('.post-btn').prop('disabled', false);
        }
    });

    $('.delete-btn').click(function() {
        $('.selected').fadeOut(300);
        $(this).prop('disabled', true);
    });

    /**
    * Click event starts here
    **/
    $('.posts').on('click', 'li', function(event) {
        $('.posts li').css('background-color', 'lightgray').addClass('selected');
        $('.delete-btn').prop('disabled', false);
    });
}

$(document).ready(main);

我知道 $('.posts li') 适用于所有创建的元素,我只是不知道如何让它仅适用于我单击的元素。

感谢您的帮助。

使用$(this).

$('.posts').on('click', 'li', function(event) {
  $(this).css('background-color', 'lightgray').addClass('selected');
  ...

只需替换这一行:

$('.posts').on('click', 'li', function(event) {
        $('.posts li').css('background-color', 'lightgray').addClass('selected');

这个:

$('.posts').on('click', 'li', function(event) {
 $(this).css('background-color', 'lightgray').addClass('selected');

$(this) 而不是 $('.posts li')