简体   繁体   English

如何使用多个变量来创建多个jquery选择器?

[英]How can multiple variables be used to create multiple jquery selectors?

When I convert multiple variables into multiple selectors the below code fails to execute. 当我将多个变量转换成多个选择器时,以下代码将无法执行。

DEMO HERE 此处演示

$('.Btn').on('click', function () {
  var outer = $(this).data('test');
  var inner = $(outer).children('.Inner');
  $(outer + ',' + inner).addClass('Success');
});

In the code above: 在上面的代码中:

This is successful 这成功了

$(outer).addClass('Success');

This is successful 这成功了

$(inner).addClass('Success');

This is not 这不是

$(outer + ',' + inner).addClass('Success');

QUESTION

How can multiple variables be used to create multiple jquery selectors? 如何使用多个变量来创建多个jquery选择器?

Your latter method will only work if both variables contain strings. 仅当两个变量都包含字符串时,后一种方法才有效。 In your case you need to use add() to join the objects held in the variables together: 在您的情况下,您需要使用add()将变量中保存的对象连接在一起:

$(outer).add(inner).addClass('Success');

Updated fiddle 更新的小提琴

In you script, outer is a string, but inner is a jQuery object. 在您的脚本中,external是一个字符串,但inner是一个jQuery对象。 You can't connect these values to each other. 您无法将这些值相互连接。 Of course, you can get the inner class name as a string, but it's a bit tricky and not always work well... 当然,您可以将内部类名称作为字符串来获取,但这有点棘手,而且并不总是能很好地工作...

If you must have the +','+ syntax, here's the solution, but as I mentioned, it's really hacky: 如果必须使用+','+语法,这是解决方案,但是正如我所提到的,它确实很hacky:

$('.Btn').on('click', function () {
    var outer = $(this).data('test');
    var inner = '.'+$(outer).children('.Inner').attr('class').split(' ')[0];
    $(outer+', '+inner).addClass('Success');
});

A better solution if you handle the inner div with something like add() or find(). 如果使用add()或find()之类的方法处理内部div,则是更好的解决方案。

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

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