[英]use variable for object name in Jquery
I found another similar question about this with a solution but it didn't work for me. 我找到了另一个与此相关的类似问题,但它对我没有用。 I am new to jquery so thanks in advance for helping me solve my noobie question.
我是jquery的新手,所以提前感谢我帮助我解决我的noobie问题。
I am trying to use a variable for the class name. 我正在尝试使用变量作为类名。 So that I can loop through the right fields based on this variable.
这样我就可以根据这个变量遍历正确的字段。 My variable returns
.reqfields4
but I get this error Error: Syntax error, unrecognized expression: "
, if I enter the value manually, it works. 我的变量返回
.reqfields4
但我收到此错误Error: Syntax error, unrecognized expression: "
,如果我手动输入值,它可以工作。
How can I achieve this? 我怎样才能做到这一点? Thanks.
谢谢。
var reqsection='\".reqfields4\"';
$(".reqfields4").each ( function() {
//$(reqsection).each ( function() {
if(( $(this).val())==''){
some code...
}
else{
some code...
}
});
You don't need quotes inside the value of the variable: 您不需要变量值内的引号:
var reqsection = '.reqfields4';
$(reqsection).each( ... );
If you have a class name — just a class name — you can add the .
如果你有一个类名 - 只是一个类名 - 你可以添加
.
: :
var reqsection = 'reqfields4'; var reqsection ='reqfields4';
$('.' + reqsection).each( ... ) $('。'+ reqsection).each(...)
Just change var reqsection='\\".reqfields4\\"';
只需更改
var reqsection='\\".reqfields4\\"';
to var reqsection='.reqfields4';
to
var reqsection='.reqfields4';
- you don't need the inner string quotes. - 您不需要内部字符串引号。
If you say var reqsection= '\\".reqfields4\\"';
如果你说
var reqsection= '\\".reqfields4\\"';
then $(reqsection).each( function() {});
然后
$(reqsection).each( function() {});
Consider it like like you told jQuery this: 考虑就像你告诉jQuery这样:
$(' ".reqfields4" ').each( function() {});
In other words you said: [ Please select now ".reqfields4" including the quotemarks ]. 换句话说,你说:[现在请选择“.reqfields4”,包括引号]。 All class selectors must start with dot(.), but you just started your jQuery selector with a quotemark (") so of course it won't work at all (it won't try to select any classes, of course), and probably would throw an error from jQuery - I don't think ANY jQuery selector string can have quotemark(") as the actual first character of the selector!.
所有类选择器必须以点(。)开头,但是你刚刚用引号(“)开始你的jQuery选择器,所以当然它根本不起作用(当然它不会尝试选择任何类),并且可能会从jQuery抛出一个错误 - 我不认为任何jQuery选择器字符串可以有quotemark(“)作为选择器的实际第一个字符!
If you do this instead: 如果你这样做:
var reqsection= ".reqfields4";
$(".reqfields4").each( function() {});
$(reqsection).each( function() {});
The above two lines are equivalent. 以上两行是等效的。
You can try like follows, 您可以尝试如下,
var reqsection=".reqfields4";
$(reqsection).each ( function() {
if(( $(this).val())==''){
some code...
}
else{
some code...
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.