Jquery:How to use variable as a selector

2019-01-20 14:55发布

问题:

I trying to figure out how can I use a variable inside a selector. If I use the actual value of the ID in the selector, it works very well.

$(document).on("click",'.tag', function(){
    var data-id = $(this).attr('data-id');

    if($('div[data-id="540"]').hasClass("tag_current")) {
        $('div[data-id="540"]').removeClass("tag_current").addClass("tag");
    }
    $(this).toggleClass('tag tag_current');
});

I checked many answers and try it in different ways, but I still didn't solve it.

回答1:

Basic string concatenation:

$('div[data-id=' + data-id + ']')