【发布时间】:2015-08-11 01:11:28
【问题描述】:
我直接将这个基本的serialize() example 复制粘贴到本地 html,它可以打印字符串(显然)。
但是我很难用这个字符串创建一个 url。我的目标是创建一个如下所示的链接(或表单操作):
<a href="node/1?single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1">Click me</a>
但是当 a 执行以下操作时:
var mylink = showValues();
document.write('<a href="node/1?'+mylink+'">Click me</a>');
...它会向我抛出“未定义”错误。
请问有大神知道怎么弄吗?
这是完整的代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>serialize demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form class="myform">
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<br>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
<br>
<input type="checkbox" name="check" value="check1" id="ch1">
<label for="ch1">check1</label>
<input type="checkbox" name="check" value="check2" checked="checked" id="ch2">
<label for="ch2">check2</label>
<br>
<input type="radio" name="radio" value="radio1" checked="checked" id="r1">
<label for="r1">radio1</label>
<input type="radio" name="radio" value="radio2" id="r2">
<label for="r2">radio2</label>
</form>
<p><tt id="results"></tt></p>
<script>
function showValues() {
var str = $( ".myform" ).serialize();
$( "#results" ).text( str );
}
$( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
$( "select" ).on( "change", showValues );
showValues();
</script>
</body>
</html>
【问题讨论】:
-
showValues返回什么? -
您对
document.write的调用看起来不错。这很可能在您的showValues函数中。你介意分享一下吗?您是否尝试过使用 Chrome 的调试器查看错误在哪里? -
嗨,我已经在 OP 中添加了完整的代码。
showValues返回此字符串:single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1(取决于表单中选择的内容)。
标签: jquery forms url serialization