使用表单输入附加 URL [英] Append URL with form input

查看:29
本文介绍了使用表单输入附加 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次尝试用 javascript 编写任何东西,虽然这完全符合预期,但我相信它可以做得更简单.并不是说这个脚本很有用,只是学习新东西的练习.我也是尽量不要用邪恶的文件写.

This is my first attempt to write anything in javascript, although this does exactly as intended, I am sure it can be done simpler. Not that this script is all that useful, just an exercise in learning something new. I was also trying not to use the evil document write.

那么更优雅的方式是什么?

So what is the more elegant way of doing this?

<html>
<body>

<input name="abc" type="text" id="foo">
<button onclick="AddInputValue()">Submit</button>

<p id="displayURL"></p>

<script>
function AddInputValue(){
var domain = "http://site.com?abc="
var qstring = document.getElementById("foo").value;
document.getElementById("displayURL").innerHTML=domain + qstring;
}
</script>
</body>
</html>

推荐答案

如果你使用 jQuery:

<html>
    <!-- Include jQuery! -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <body>
        <form id="form1">
            <input name="abc" type="text" id="foo">
            <button type="submit">Submit</button>
        </form>

        <p id="displayURL"></p>

        <script>
            $(document).ready(function () {
                var form = document.getElementById("form1");
                $(form).submit(function () {
                    var domain = "http://site.com/?";
                    var data = $(this).serialize();

                    document.getElementById("displayURL").innerHTML = domain + data;

                    return false;
                });
            });
        </script>
    </body>
</html>

您甚至可以添加更多表单元素,元素的name 将匹配查询字符串.http://jsfiddle.net/3muu6/

You can even add more form elements and the name of the element will match the query string. http://jsfiddle.net/3muu6/

这篇关于使用表单输入附加 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆