2014-07-12 2 views
1

양식 및 목록의 값을 추적하려고합니다. 나는 jQuery를 사용한다. 양식을 serialize 할 수는 있지만 목록과 동일한 작업을 수행하는 데 문제가 있습니다. 누군가가 그 목록을 serialize하는 것을 도울 수 있습니까?양식 및 목록 serialize

나는 확인하고 재생하려면 여기 샘플이 있습니다 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); 
}); 

답변

1

jQuerys serialize 그냥 폼 요소입니다. 읽을 수 있듯이 http://api.jquery.com/serialize/.

선택기 $("list")이 옳지 않습니다. list은 식별자이므로 셀렉터는 다음과 같아야합니다 : $("#list").

모든 항목을 반복하고 문자열에 추가하여 목록을 직접 serialize하지 않는 이유는 무엇입니까? 이 예처럼 (깊이 돌보는없이) :

$("#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); 
}); 
+0

그것은 작동하지만 내가 그것을 이해하지 못하는 아래 코드를 작업. 나는 단지 배우기 만하고 너무 복잡합니다. 각 부분에 대한 정보를 찾으려고 노력할 것입니다. – Nrc

+0

@Nrc 모든 줄을 설명하기 위해 몇 가지 설명을 추가했습니다. 희망이 당신을 도울 것입니다. – dersvenhesse

1

할 수 있습니다 하지 직렬화 목록 (http://api.jquery.com/serialize). 또한, 제공 jsfiddle에, 나는 다음과 같은 관찰 가지고 : list 이후 selector

  • 사용 $('#list') 대신 $('list') 당신의 요소의 id입니다.

  • </ul> 끝 태그가 없습니다.


이 시도 :

라이브 데모 :http://jsfiddle.net/rTgL3/4/


array에 저장 각 요소의 id=text을 반환하여 #list 내부의 모든 li 요소를 가져옵니다.

var array = $('#list li').map(onListMap).get(); 
var qStr = array.join('&'); // queryString needed 

onListMap 기능 :

function onListMap(idx, el) { 
    return el.id + '=' + $(el).text(); // Use '.html()' if needed 
}; 
1

가 먼저 JSON 객체를 생성하고 직렬화 PARAM을 사용해야합니다.

$("#buttonForm").click(function(){ 
    var dataForm = $("form").serialize(); 
    alert(dataForm); 
}); 

var myObject = {}; 
$("#list li").each(function(){ 
    var t = $(this).attr('id') 
    myObject[t]=$(this).html(); 
}); 

$("#buttonList").click(function(){ 
    alert($.param(myObject)); 
}); 

갱신 http://jsfiddle.net/rTgL3/4/

+0

나는 ID로 키를 사용했고 HTML을 값으로 사용했다. 요구 사항에 따라 ID를 변경할 수있다. –