迭代数组并打印html foreach键/值Javascript / jQuery

时间:2015-05-02 06:19:09

标签: javascript jquery iteration

好的,所以这个功能正在做我期望的一切,直到我点击打印到html部分。无论出于何种原因,它只会打印出一个索引,而不是打印数组中的每个索引。

此代码的违规部分位于包含的代码段中的第19-23行。

Multiply



$.each(_services, function(index,value)
{
    $('#test').html('<p>' +index+ ":" +value+ '</p>');
});
&#13;
// services object -- initially EMPTY
var _services = {};

$('#serviceList input[type=checkbox]').change( function serviceList()
{
	// For each checkbox inside the #serviceList container, do the following
	$(this).each( function()
	{
		// Set "_key" to id of checkbox
		var _key = (this).id;

		// If checkbox is checked -- ADD -- its key/value pair to the "services" object
		// else checkbox is unchecked -- DELETE -- key/value pair from "services" object
		(this.checked) ? _services[ _key ] = (this).value : delete _services[ _key ];

		// console.log(_services);
	}); // END foreach()

	// foreach services print paragraph to display key/value
	$.each(_services, function(index,value)
	{
		$('#test').html('<p>' +index+ ":" +value+ '</p>');
    }); // END services foreach
  
}); // END serviceList()
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

每次写新行时,您都在清空容器innerHTML。相反,您应该在each循环之前append内容并清除容器:

$('#test').empty(); 
$.each(_services, function(index,value) {
    $('#test').append('<p>' +index+ ":" +value+ '</p>');
});

查看下面的演示:

&#13;
&#13;
var _services = {};

$('#serviceList input[type=checkbox]').change(function serviceList() {
    // For each checkbox inside the #serviceList container, do the following
    $(this).each(function () {
        // If checkbox is checked -- ADD -- its key/value pair to the "services" object
        // else checkbox is unchecked -- DELETE -- key/value pair from "services" object
        this.checked ? _services[this.id] = this.value : delete _services[this.id];

        // console.log(_services);
    }); // END foreach()

    // foreach services print paragraph to display key/value
    $('#test').empty();
    $.each(_services, function (index, value) {
        $('#test').append('<p>' + index + ":" + value + '</p>');
    });

}); // END serviceList()
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul id="serviceList"> <!-- changed to list in the tutorial -->
  <li><input id="id_a" type="checkbox" value="40"> Test A</li>
  <li><input id="id_b" type="checkbox" value="50"> Test B</li>
  <li><input id="id_c" type="checkbox" value="60"> Test C</li>
  <li><input id="id_d" type="checkbox" value="70"> Test D</li>
</ul>

<div id="test" style="height: 150px; background-color: pink;"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果正确理解您的问题,这是因为您每次都要覆盖#test元素的内容。如何追加:

   $('#test').append('<p>' +index+ ":" +value+ '</p>');