我尝试跟踪表单和列表的值。我使用 jQuery。我可以序列化表单,但对列表执行相同操作时遇到问题。有人可以帮忙序列化该列表吗?
我这里有示例可以检查和播放:http://jsfiddle.net/rTgL3/
HTML:
<form action="">
<input type="text" name="item-1" value="item1" /><br>
<input type="text" name="item-2" value="item2" /><br>
<input type="text" name="item-3" value="item3" /><br>
</form>
<div id="buttonForm">Serialize form</div>
<br><br>
<ul id="list">
<li id="item_1">Item1</li>
<li id="item_2">Item2</li>
<li id="item_3">Item3</li>
</ul>
<div id="buttonList">Serialize list</div>
JQUERY:
$("#buttonForm").click(function(){
var dataForm = $("form").serialize();
alert(dataForm);
});
$("#buttonList").click(function(){
var dataList = $("list").serialize();
alert(dataList);
});
最佳答案
jQuerys serialize
仅适用于表单元素。您可以在这里阅读: http://api.jquery.com/serialize/ .
此外,您的选择器 $("list")
不太正确。 list
是一个标识符,因此选择器应如下所示:$("#list")
。
为什么不通过迭代所有项目并将它们附加到字符串来自己序列化列表?就像这个例子(不关心深度):
$("#buttonList").click(function() {
// empty string to save the result
var dataList = "";
// find all li elements within the element with the id list
var $entries = $("#list").find('li');
// iterate through all these items, with i as index and item itself as entry
$entries.each(function(i, entry) {
// append the elements id attribute and its content to the string, like: item_1=Item1 for <li id="item_1">Item1</li>
dataList += $(entry).attr('id') + '=' + $(entry).text();
// add & to the string, if the entry is not the last one
if (i != $entries.length-1) {
dataList += '&';
}
});
// alert the result string
alert(dataList);
});
关于jquery - 序列化表单和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713871/