jQuery一个接一个地影响元素,而不是影响被点击的元素

时间:2016-11-22 07:21:59

标签: php jquery

我正在动态地回应一些READ_SMS标签:

[
      'attribute' => 'Icon',
      'format' => 'html',
      'label' => 'Icon',
      'value' => function ($data) {
      return Html::img(Yii::$app->request->BaseUrl.'/uploads/path/' . $data['Icon'],
      ['width' => '60px']);
     },
],

我想这样做,以便当用户点击所选div中的加号按钮时,只有该div受到影响。到目前为止,当我这样做时,它会按顺序影响元素,nomatter加上我点击。这里是jQuery:

div

4 个答案:

答案 0 :(得分:2)

您可以使用event事件中的click对象来获取所点击元素的ID。

$(document).ready(function(){
        $('.fa-plus').click(function(evt){
                counter = 0;
                id      = evt.target.id;

                if($(this).attr("id") != id){
                    return;
                }

                counter = counter+1;
                $("#" + id).css('color','green');
                $('#votes-count').parent().html(counter);
                alert(id);                  
        });
});

您可以参考here以获取有关传递的event对象的更多信息。

答案 1 :(得分:2)

您的元素包含重复的ID:<div class="col-md-4"><i class="fa fa-plus fa-fw"></i>

请检查我的jsfiddle。您需要使用HTML结构修复选择器。

祝你好运;)

答案 2 :(得分:1)

首先,不允许多次使用相同的ID。 ID始终是唯一的。所以你可以用类做这样的事情:

$counter = 0;
foreach($applications as $application) {
    echo sprintf(
         '<div class="col-md-4">'
             . '<h4 class="list-group-item-heading remove-margin">'
             . '<i class="fa fa-plus fa-fw" data-myattr="%s"> </i>'
             . '</h4>'
             . '</div>',
         $counter++
    );
}

然后您可以将您的点击事件订阅者附加到:

$(document)
        .ready(function () {
            $("i[data-myattr]")
                .click(function () {
                    counter = 0;
                    id = $(this).data("myattr");
                    $(this).css("color", "green");
                    $("#votes-count").parent().html(++counter);
                    alert(id);
                }
            );
        }
);

那应该有用。祝你好运!

答案 3 :(得分:0)

您也可以针对每个fa-plus进行迭代,然后将每个{。}组合点击。

Als使用 attr 代替 prop

访问ID
$(document).ready(function(){
    $('.fa-plus').each(function(){
        $(this).click(function(){
            counter = 0;
            id = $(this).closest('div').attr("id");
            counter = counter+1;
            $(this).css('color','green');
            $('#votes-count').parent().html(counter);
            alert(id);                  
        });
    });
});