I am trying to add values to a simple array, but I can't get the values pushed into the array.
So far so good, this is the code I have:
codeList = [];
jQuery('a').live(
'click',
function()
{
var code = jQuery(this).attr('id');
if( !jQuery.inArray( code, codeList ) ) {
codeList.push( code );
// some specific operation in the application
}
}
);
The above code doesn't work! But if I manually pass the value:
codeList = [];
jQuery('a').live(
'click',
function()
{
var code = '123456-001'; // CHANGES HERE
if( !jQuery.inArray( code, codeList ) ) {
codeList.push( code );
// some specific operation in the application
}
}
);
It works!
I can't figure out what's going on here, because if I do other tests manually it also work!
-
1Include the HTML. I am quite sure that is where the problem lies.iambriansreed– iambriansreed2012年09月21日 16:02:08 +00:00Commented Sep 21, 2012 at 16:02
-
3Starting an ID with a digit is invalid if you're using XHTML or a doctype prior to HTML5.Fabrício Matté– Fabrício Matté2012年09月21日 16:03:36 +00:00Commented Sep 21, 2012 at 16:03
2 Answers 2
Try this .. Instead of cheking for bool check for its index.. It returns a -1 when it is not found..
var codeList = [];
jQuery('a').live(
'click',
function()
{
var code = '123456-001'; // CHANGES HERE
if( jQuery.inArray( code, codeList ) < 0) { // -ve Index means not in Array
codeList.push( code );
// some specific operation in the application
}
}
);
Comments
jQuery.inArray returns -1 when the value is not found, also .live is deprecated on jQuery 1.7+ and you're missing a var statement in your codeList declaration. Here's a rewrite of your code:
//without `var`, codeList becomes a property of the window object
var codeList = [];
//attach the handler to a closer ancestor preferably
$(document).on('click', 'a', function() {
//no need for attributes if your ID is valid, use the element's property
var code = this.id;
if ($.inArray(code, codeList) === -1) { //not in array
codeList.push(code);
}
});
And as I stated in the question comments, IDs starting with a digit are illegal unless you're using the HTML5 doctype.
3 Comments
var keyword even then. Without any var statement, your code won't pass JSHint/Lint, generate errors in strict mode and codeList will be created as a property of window object without the DontDelete attribute flag.var statement, ignore the comment above.