简体   繁体   中英

Can't use dynamic variable into JQuery function

I want to disable TableSorter plugin on some th. These th have class="disableSorter", so I do:

$('.disableSorter').each(function(index) {

    $('.tablesorter').tablesorter({ headers: { index: { sorter: false} } }); 

});

where index: is the index variable passed in the function. The thing is " index " is not replaced by the number (for example 0:, 1: 5:, etc.)

Thanks for help!

===== Edit =====

Thanks JaredPar, your solution was right about the dynamic variable. I had to edit the code because I wan't getting the index of the th element, but the index of the each loop.

Here's my final code

var inner = {};
$('.disableSorter').each(function() {
    inner[$('.tablesorter th').index(this)] = { sorter: false };
});

$('.tablesorter').tablesorter({ headers: inner  }); 

The problem here is you're trying to use the value in a place where javascript is not looking for values but instead for literals to use as names. You need to use the [] syntax to create a named member based on a value.

Try the following

$('.disableSorter').each(function(index) {
  var inner = {};
  inner[index] = { sorter: false };
  $('.tablesorter').tablesorter({ headers: inner); 

});

Try this

var obj = null;
$('.disableSorter').each(function(index) {
    obj = {};
    obj.headers = {};
    obj.headers[index] = { sorter: false };
    $('.tablesorter').tablesorter(obj); 

});

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