Use variable in jQuery selector [duplicate]

一个人想着一个人 提交于 2019-12-01 13:47:50

问题


In the function below, I'd like the idurl be the word apple with a suffix. The suffix is number containing a number. Example would be apple12.

But in the function below, I have trouble concatenating the variable number with the word apple.

function apple(number) {
  if (something === "0") {
    $('.onchange :checkbox[idurl="apple" + number]').prop('checked', false);
  } else {
    $('.onchange :checkbox[idurl="apple" + number]').prop('checked', true);
  }
};

I tried using extra " or [] but it hasn't been very succesfull so far. The variable number is not bein recognized as a variable and thus not concatenated with the word apple.


回答1:


use

$('.onchange :checkbox[idurl="apple"' + number+']').prop('checked', false);

Breaking of string:

1st part '.onchange :checkbox[idurl="apple"'

2nd part number

3rd part of string ']'.




回答2:


I believe it's because it is inside your single quotes. Try this instead:

$('.onchange :checkbox[idurl="apple"' + number + ']').prop('checked', false);



回答3:


You need to call the function with an actual number where your number argument in the function is. Also, javascript doesn't recognize variables in quotes, so you need to escape your single quotes.

$('.onchange :checkbox[idurl="apple"' +number +']').prop('checked', false);



来源:https://stackoverflow.com/questions/26805501/use-variable-in-jquery-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!