简体   繁体   English

jQuery 选择器使用多个 data-* 属性选择器

[英]jQuery selector using multiple data-* attribute selectors

I want to use an attribute-selector, created dynamically from a variable, but it only react to the beginning of string in the variable (the non-dynamic portion):我想使用一个从变量动态创建的属性选择器,但它只对变量中字符串的开头(非动态部分)作出反应:

var dataKeys = 'td[data-key="name"],td[data-key="code"],td[data-key="date"]';
dataKeys = dataKeys + ',td[data-key="' + fieldsArray[i] + '"]';

And when I use it as follows:当我按如下方式使用它时:

$(dataKeys, this).each(function ()

It only reacts to attribute-values of "name" , "code" and "date" keys, when dataKeys:当 dataKeys: 时,它只对"name""code""date"键的属性值做出反应

td[data-key="serial_no"], td[data-key="name"], td[data-key="code"], td[data-key="date"], td[data-key="serial_no"]"

I got your code parts to work inside 1 snippet.我让你的代码部分在 1 个片段中工作。 I only had 1 problem at first: my browser stripped the TD elements because they where not inside a proper html table table, and so the selector did not find the td s起初我只有一个问题:我的浏览器删除了TD元素,因为它们不在正确的 html 表格中,因此选择器没有找到td s

So i put it inside a table and it worked.所以我把它放在一张桌子里,它起作用了。 (see snippet below). (见下面的片段)。

Most probably the error is somewhere else in your code.错误很可能在您的代码中的其他地方。 maybe its good to add some logging or debug and see which values your variables have.添加一些日志记录或调试并查看变量具有哪些值可能会很好。 I only give you 1 possible solution.我只给你1个可能的解决方案。

 var fieldsArray = ['dynamic', 'serial_no']; var dataKeys = 'td[data-key="name"],td[data-key="code"],td[data-key="date"]'; dataKeys = dataKeys + ',td[data-key="' + fieldsArray[1] + '"]'; console.log('selector', dataKeys); $(dataKeys).each(function() { console.log('i am', this); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td data-key="name">hey</td> <td data-key="code">hi</td> <td data-key="excluded">hoho</td> <td data-key="serial_no">hoho</td> <tr> <table>

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

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