简体   繁体   English

自定义数据属性选择器不起作用

[英]Custom data-attribute selector not working

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+']")); 成功打印profile_following然而,如果我尝试选择一个带有属性选择器的链接,这个变量就像这个console.log($("a[data-target='+attr+']")); it can't find the element! 它找不到元素!

And the weirdest thing after all is if I hardcode the line like that console.log($("a[data-target='profile_following']")); 而最奇怪的是,如果我像console.log($("a[data-target='profile_following']"));一样对该行进行硬编码console.log($("a[data-target='profile_following']")); it finds the object successfully. 它成功找到了对象。

Any idea why the same line wouldn't work with the +attr+ inside the attribute selector? 知道为什么同一行不适用于属性选择器内的+attr+

You need to use string concatenation to create a string with a value of "a[data-target='profile_following']" . 您需要使用字符串连接来创建值为"a[data-target='profile_following']"的字符串。 You do that with: 你这样做:

$('a[data-target="'+attr+'"]');

In your example, +attr+ is part of the string because you never closed and reopened your quotes. 在您的示例中, +attr+是字符串的一部分,因为您从未关闭并重新打开引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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