[英]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. 我正在尝试将选定的类添加到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. 当我将
loc
插入查询a[href
选择器时,即使loc
提供了正确的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");
我想将loc放到选择器中,像这样
$('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: 这是基本的JavaScript字符串连接:
var loc = "6";
'a[href$=""+loc]' //-> 'a[href$=""+loc]' oops
'a[href$="'+loc+'"]' //-> 'a[href$="6"]' yay!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.