isset($_GET['var']) 的 jQuery 等效项

let*_*ngo 6 jquery

我目前有一个 jQuery 函数,我需要知道是否存在任何GET数据。我不需要查询字符串中的数据,只需要是否有任何数据可以运行两个函数之一。

等效 PHP:

if (isset($_GET['datastring'])) {
    // Run this code
} else {
    // Else run this code
}
Run Code Online (Sandbox Code Playgroud)

Kar*_*arl 6

您必须尝试类似的操作:(您不必使用变量,但如果您愿意,可以使用)

$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

if ($.urlParam('variable_name') != '') {  // variable_name would be the name of your variable within your url following the ? symbol
    //execute if empty
} else {
    // execute if there is a variable
}
Run Code Online (Sandbox Code Playgroud)

如果您想使用变量:

// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null
Run Code Online (Sandbox Code Playgroud)