javascript 如何从html页面中的url获取参数并将其显示在textarea中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17609279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:57:26  来源:igfitidea点击:

how to get parameters from url in html page and display it in a textarea?

javascripthtmlajax

提问by user2575379

am using following javascript function in my html page and i want to display parameters properly without any concatenation operators in the textarea....

我在我的 html 页面中使用了以下 javascript 函数,我想在 textarea 中没有任何连接运算符的情况下正确显示参数....

<html>
    <head>
        <script type="text/javascript">
            function getParameter(paramName) {
                var searchString = window.location.search.substring(1), i, val, params = searchString.split("&");

                for ( i = 0; i < params.length; i++) {
                    val = params[i].split("=");
                    if (val[0] == paramName) {
                        return val[1];
                    }
                }
                return null;
            }

            function getUrlData() {
                var comment = getParameter("comment");
                document.getElementsByName("my-textarea")[0].value = comment;
            }

        </script>
    </head>
    <body onload="getUrlData()">
        <h1>welcome</h1>
        <textarea name="my-textarea" readonly rows="5" cols="30"> </textarea>       


    </body>
</html>

回答by shamcs

try this

试试这个

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}