javascript 自定义数据属性选择器不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9282162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom data-attribute selector not working
提问by matt
Any idea why this happens …
知道为什么会发生这种情况……
var attr = $(this).data('link');
console.log(attr); // profile_following
console.log($("a[data-target='profile_following']")); // found the object
console.log($("a[data-target='+attr+']")); // [] empty
Inside of a click handler I have the lines above!
console.log(attr);
successfully prints profile_following
However if I try to select a link with an attribute selector and this variable like this console.log($("a[data-target='+attr+']"));
it can't find the element!
在点击处理程序内部,我有上面的几行!
console.log(attr);
成功打印profile_following
但是,如果我尝试选择一个带有属性选择器的链接,并且像这样的变量console.log($("a[data-target='+attr+']"));
找不到该元素!
And the weirdest thing after all is if I hardcode the line like that console.log($("a[data-target='profile_following']"));
it finds the object successfully.
毕竟最奇怪的是,如果我像这样硬编码该行,console.log($("a[data-target='profile_following']"));
它会成功找到对象。
Any idea why the same line wouldn't work with the +attr+
inside the attribute selector?
知道为什么同一行不能与+attr+
属性选择器内部一起使用吗?
回答by zzzzBov
You need to use string concatenation to create a string with a value of "a[data-target='profile_following']"
. You do that with:
您需要使用字符串连接来创建一个值为 的字符串"a[data-target='profile_following']"
。你这样做:
$('a[data-target="'+attr+'"]');
In your example, +attr+
is part of the string because you never closed and reopened your quotes.
在您的示例中,+attr+
是字符串的一部分,因为您从未关闭并重新打开您的引号。