Jquery在一组具有相同类名的元素中选择clicked元素

问题描述:

也许你们可以帮我解决这个问题,我在过去30分钟里一直在努力。

Maybe you guys can help me out with this, I've been struggling with it for the past 30 minutes.

假设我有四个具有相同类别的元素。

Let's say I have four elements with the same class.

<div class="test">hi</div>
<div class="test">hey</div>
<div class="test">yo</div>
<div class="test">What's up</div>

如何选择点击的那个?

我可以这样工作:

$('.test').click(function() {
    $(this).toggleClass("btn-danger btn-success");
});

但是,我需要它来启动,而不需要在ajax调用后点击成功,因此我需要能够做这样的事情(失败的尝试):

However, I need it to fire without being clicked on success after an ajax call, so I need to be able to do something like this (failed attempts):

$('.test', this).toggleClass("btn-danger btn-success"); // This did not work

$(this).find('.test').toggleClass("btn-danger btn-success");  // Also did not work

有任何建议吗?非常感谢!

Any suggestions? Thanks so much!!

这听起来像ajax调用是当一个元素被点击,在ajax调用中传递不同的值,具体取决于单击哪个元素。不要使用onclick属性,您可以执行以下操作:

It sounds like the ajax call is made when one of the elements is clicked, but you need to pass different values in the ajax call depending on which element is clicked. Rather than use an "onclick" attribute, you could do the following:

HTML:

<div class="test" data-param1="value1a" data-param2="value2a">hi</div>
<div class="test" data-param1="value1b" data-param2="value2b">hey</div>
<div class="test" data-param1="value1c" data-param2="value2c">yo</div>
<div class="test" data-param1="value1d" data-param2="value2d">What's up</div>

JavaScript:

JavaScript:

$('.test').click(function() {
    var $div = $(this);
    $.ajax(url, {
        data: {
            param1: $div.attr('data-param1'),
            param2: $div.attr('data-param2')
        },
        success: function() {
            $div.toggleClass("btn-danger btn-success");
        }
    });
});

当然,您可以设置 data - 属性使用PHP变量。

Of course, you would set the values of the data- attributes using PHP variables.