I have the following to launch dialogs in my app:
$('.dialogDo').live('click', function() {
// Do we have a custom width?
var width = this.search.match(/width=(\d+)/)[1];
if (width) {
dialogDo(this.href, width);
}
else {
dialogDo(this.href, 480);
}
return false;
});
This works fine if width is defined in the href which trigger the click function above. Problem is if width is not defined it breaks. How can开发者_JAVA百科 I deal with an undefined width while still maintaining the functionality to use a width if provided?
Thanks
One option is to have a default width in place.
var matched = this.search.match(/width=(\d+)/);
var width = matched ? matched[1] : DEFAULT_WIDTH;
Edit -- match can return null if there are no matches and you can't index into null. (thanks @Chris)
The javascript match function returns null if it doesn't match and an array of results if so. So you need to check that the result is actually an array before indexing it with [1]
. For example:
var width = this.search.match(/width=(\d+)/);
if (width) {
dialogDo(this.href, width[1]);
}
else {
dialogDo(this.href, 480);
}
Try this
$('.dialogDo').live('click', function() {
// Do we have a custom width?
var width = this.search.match(/width=(\d+)/)[1];
if (!isNaN(width)) {
dialogDo(this.href, width);
}
else {
dialogDo(this.href, 480);
}
return false;
});
精彩评论