I am having trouble using variables in jQuery class selectors. The following works:
$('.contactcapturepage > .question-container > .select-container > select').each(function () {...
But the following doesn't work
var pageType='.contactcapturepage';
$(pageType+' > .question-container > .select-container > select').each(function () {...
How can I use variables within my class selector hierarchy?
Thanks.
EDIT: In response to request for more code: I'm calling a helper function as follows:
helper_FormMapper(existing.contact, 'objectToForm','.contactcapturepage');
The helper signature:
function helper_FormMapper(object,direction,pageType) {
And then later in the same function:
//$('.contactcapturepage > .question-container > .select-container > select').each(function () {
$(pageType+' > .question-container > .select-container > select').each(function () {
var propertyname = $(this).attr('name');
$.log('processing select:'+propertyname);
if (propertyname != 'country'
&& propertyname != 'state') {
if (direction == 'objectToForm') {
$("select#" + propertyname + " option").each(function () { this.selected = (this.text == object[propertyname]); });
}
else {
object[propertyname] = $('#' + propertyname + ' :selected').text();
}
}
});
Note that the commented-out line works, whilst the uncommented version does not work.
EDIT - After further testing the following also does not work:
var path = pageType + ' > .question-container > .text-container > input';
$(path).each(function () {...
EDIT - But the following DOES work:
var path = '.contactcapturepage > .question-container > .text-container > input';
$(path).each(function () {...
What's going on here!
开发者_C百科EDIT: The following also works
pageType = '.contactcapturepage';
$(pageType + ' > .question-container > .text-container > input').each(function () {
, so it looks like it's nothing to do with jQuery, but something to do with the function parameter getting corrupted somewhere. Outputting pageType to the console shows it as undefined.
EDIT - Ok - lots of egg on face - bug in my code... Very sorry to have wasted your time
I can't commento so I'll have to write it as an answer. Are you sure that the function inside each() is not being invoked, perhaps it is but you are getting some exception inside it.
if you are using chrome, then I'd set a breakpoint in this line
$(pageType+' > .question-container > .select-container > select')
then I'd run this in the console
$(pageType+' > .question-container > .select-container > select').length
精彩评论