[英]Append URL with form input
這是我第一次嘗試用javascript編寫任何東西,盡管這樣做確實符合預期,但我相信它可以更簡單地完成。 並不是說這個腳本很有用,只是一個學習新知識的練習。 我也試圖不使用邪惡的文件寫。
那么,這樣做的更優雅的方法是什么?
<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/
只需將示例發布在http://jsfiddle.net/3muu6/中 。
增加了輸入數量。 這基本上就是Google Analytics(分析)URL Builder的工作,並且是本練習的靈感。
<html>
<head>
<!-- Include jQuery! -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
<body>
<form id="form1">
<input name="abc" type="text" id="foo" /><br />
<input name="def" type="text" id="bar" /><br />
<input name="ghi" type="text" id="tar" /><br />
<input name="jkl" type="text" id="boo" /><br />
<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://example.com/?";
var data = $(this).serialize();
document.getElementById("displayURL").innerHTML = domain + data;
return false;
});
});
</script>
</body></html>
現在,當用戶將輸入值留空時,如何省略查詢字符串對? 嗯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.