0

我想向 url 添加参数,因为我有 2 个文本框和一个按钮,我无法弄清楚我卡在哪里并且无法向 url 添加参数
这是我的代码:

HTML:

Param Name: <input id="tbAddParam" type="text" /><br>
Param Value: <input id="tbAddParamValue" type="text" /><br>
<input onclick="javascript:AddParamter();" value="Add" type="button" />

JavaScript:

function AddParamter() {
    var new_url = AddUrlParameter(window.location.href, document.getElementById('tbAddParam').value, document.getElementById('tbAddParamValue').value);
    window.location.href = new_url;
}

function AddUrlParameter(a, b, c) {
    if (b.trim() == "") {
        alert("Parameter name should not be empty.");
        return a;
    }
    if (c.trim() == "") {
        alert("Parameter value should not be empty.");
        return a;
    }
    if (a.indexOf("?") == -1) {
        return a + "?" + b + "=" + c;
    }
    var d = a.split("?");
    if (d.length >= 2) {
        if (d[1].trim() == "") {
            return d[0] + "?" + b + "=" + c;
        }
        var e = d[1].split(/[&;]/g);
        for (var f = 0; f < e.length; f++) {
            var g = e[f]; var h = g.split("=");
            if (h.length >= 2) {
                if (h[0] == b) {
                    alert("Url Parameter with provided name already exists! Try Updating that Url Parameter.");
                    return a;
                }
            }
        }
        return a + "&" + b + "=" + c;
    }
}
4

4 回答 4

1

在 IE 中运行时(我在 IE 10 中对此进行了测试),您需要允许被阻止的内容才能运行 JavaScript。否则将不允许 JavaScript 运行。Luiggi Mendoza 对 IE 9 提出了同样的建议。

值得注意的是,这在 Chrome 和 FireFox 中运行良好,无需任何用户确认允许 JavaScript 运行。

于 2013-02-25T06:38:16.833 回答
1

IE 不喜欢“.trim()”。我在 IE8 中使用 IE8 兼容模式进行了测试,您的代码由于修剪而无法正常工作。虽然我认为 IE9 很好(正如 Luigi 的确认所指出的那样)。

改用这样的东西:

strReplace=str.replace(/^\s+/,'').replace(/\s+$/,''); 

您可以通过以下方式解决它:

function stripWhiteSpace(arg){
   if(arg.replace(/^\s+/,'').replace(/\s+$/,'') == ""){
      return true;
   }
}

然后只需调用它并传递您的参数

if (stripWhiteSpace(b))
于 2013-02-25T06:40:35.203 回答
1

从上面的评论:

我已经测试了您的代码并为我工作(如果页面以 html、jsp 或 .something 结尾)。这是使用 Chrome v25 测试的。

后来,我在 IE9 上进行了测试,它在为本地执行页面启用脚本执行后工作。进入 IE 时会弹出一条消息。在 IE9 中,底部显示Internet Explorer 限制此网页运行脚本或 ActiveX 控件。在右边有这个选项允许被阻止的内容。.

对于 IE 向后兼容性,您似乎应该替换james emanon's answerd[1].trim()中所述的内容。

作为建议,至少使用两个浏览器来测试您的网页。是的,我强烈建议在 IE 上进行测试,因为它会给你一个很好的(?)反馈,因为它对脚本错误如此敏感(它会出现很多错误,Chrome 和 Firefox 会为你覆盖)。

于 2013-02-25T06:45:33.157 回答
1

我支持@rhughes 的回答。但是,如果您在 IE8 中测试此代码(我正在使用此代码,但您的代码无法正常工作)及以下,HTML trim() 将无法正常工作。由于您在 3 个地方有 trim(),因此您必须使用以下内容。

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

或者您可以更轻松地使用 jQuery trim()

$.trim()

参考 1

参考2

于 2013-02-25T07:25:08.327 回答