如何处理未定义的查询变量

how to deal with an undefined query variable

本文关键字:未定义 查询 变量 处理 何处理      更新时间:2023-09-26

在我的应用程序中启动对话框:

$('.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;
});

如果在href中定义了触发上面的click函数的宽度,则可以正常工作。问题是,如果宽度没有定义它打破。我如何处理未定义的宽度,同时仍然保持使用宽度的功能,如果提供?

谢谢

一个选择是设置一个默认宽度。

var matched = this.search.match(/width=('d+)/);
var width = matched ? matched[1] : DEFAULT_WIDTH;

Edit——match可以返回null如果没有匹配,你不能索引到null。(感谢@Chris)

javascript match函数如果不匹配则返回null,如果匹配则返回结果数组。所以你需要在用[1]索引它之前检查结果实际上是一个数组。例如:

var width = this.search.match(/width=('d+)/);
if (width) {
    dialogDo(this.href, width[1]);
}
else {
    dialogDo(this.href, 480);
}

试试这个

$('.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;
});