Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

Basic string concatenation:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...