简体   繁体   中英

How to add a variable to an a href selector in jQuery?

I'm trying to add a selected class to a post in ruby on rails.

When I insert loc into the query a[href selector it doesn't work even though loc is giving the correct url.

$(document).ready ->
    jQuery ->
        loc = location.href.substring(7)
        loc = loc.substring(loc.indexOf("/"))
        $('a[href$="posts?page=6"]').addClass("selected");

I want to put loc into the selector, like this $('a[href$=""+loc]').addClass("selected");

But it's not applying the selected class. Any help?

CoffeeScript具有字符串插值,因此您可以执行以下操作:

$("a[href$='#{loc}']").addClass("selected")

This is basic JavaScript string concatenation:

var loc = "6";
'a[href$=""+loc]'    //-> 'a[href$=""+loc]'  oops
'a[href$="'+loc+'"]' //-> 'a[href$="6"]'     yay!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM