简体   繁体   中英

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:

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. 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

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.

 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>

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