jQuery selector with variable in the selector

2019-07-16 15:27发布

Quick and silly jQuery selector question.

Why this does not work: jsFiddle demo

//config
var ThisTable = $('.ReallyLongSillyTableName');


// Function
$(ThisTable + ' > tbody > tr > td:last-child').each(function() {
    $(this).append('Sales Orders: ');
});

But, this does work: jsFiddle demo

$('.ReallyLongSillyTableName td:last-child').each(function() {
    $(this).append('Some Text');
});

Any suggestions much appreciated.

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-16 15:27

You can use either this:

$('tbody > tr > td:last-child', ThisTable).each(function() {
    $(this).append('Sales Orders: ');
});

or this:

ThisTable.find('tbody > tr > td:last-child').each(function() {
    $(this).append('Sales Orders: ');
});
查看更多
Summer. ? 凉城
3楼-- · 2019-07-16 15:41
  1. var ThisTable = $('.ReallyLongSillyTableName'); is jQuery object (javascript object)

  2. $(ThisTable + ' > tbody > tr > td:last-child') here in () you have javascript object + string, that will not give you full string (NOT string + string!)

  3. You need var ThisTable = '.ReallyLongSillyTableName';

查看更多
来,给爷笑一个
4楼-- · 2019-07-16 15:43

$('.ReallyLongSillyTableName'); is a jQuery object, so you can't use it as String.

So try

var ThisTable = '.ReallyLongSillyTableName';


// Function
$(ThisTable + ' > tbody > tr > td:last-child').each(function() {
    $(this).append('Sales Orders: ');
});

$(ThisTable + ' td:last-child').each(function() {
    $(this).append('Some Text');
});

and you can use ThisTable as above or $(ThisTable) (to make it jquery object) for other purpose.

查看更多
对你真心纯属浪费
5楼-- · 2019-07-16 15:47

Try like below,

ThisTable.find('tbody > tr > td:last-child').each(function() {
    $(this).append('Sales Orders: ');
});
查看更多
登录 后发表回答