jquery - 序列化表单和列表

标签 jquery

我尝试跟踪表单和列表的值。我使用 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/

相关文章:

jquery - 移动和隐藏/显示谷歌地图 div 的成本

jquery - owl-carousel 从不显示元素

javascript - 如何从父窗口中的 iframe(Sharepoint 托管应用程序,(应用程序部分)))打开模式对话框弹出窗口

javascript - 如果选择了另一个选择菜单的值,则显示隐藏的选择菜单

javascript - 无法使用 JSONP 从 API 以随机顺序获取详细信息

jquery - jQuery 可以返回特定子元素为空的所有元素吗?

javascript - 为什么用 Ajax 响应替换页面内容时不应用 jQuery 插件?

javascript - 嵌套的 $(document).ready() 和 $(window).load() 事件之间的区别

jquery - Reveal Modal 不适用于 IE(代码中没有动画)

javascript - 我如何从跨度中获取 php 值(id)并在模式窗口中使用它