Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
遍历数组并打印html foreach键/值Javascript/jQuery_Javascript_Jquery_Iteration - Fatal编程技术网

遍历数组并打印html foreach键/值Javascript/jQuery

遍历数组并打印html foreach键/值Javascript/jQuery,javascript,jquery,iteration,Javascript,Jquery,Iteration,好的,这个函数正在做我所期望的一切,直到我点击打印到html部分。无论出于何种原因,它一次只打印一个索引,而不是打印数组中的每个索引 这段代码中有问题的部分位于包含的代码段的第19-23行 $.each(_services, function(index,value) { $('#test').html('<p>' +index+ ":" +value+ '</p>'); }); $。每个(\u服务、功能(索引、值) { $('#test').html(''+i

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

这段代码中有问题的部分位于包含的代码段的第19-23行

$.each(_services, function(index,value)
{
    $('#test').html('<p>' +index+ ":" +value+ '</p>');
});
$。每个(\u服务、功能(索引、值)
{
$('#test').html(''+index+“:“+value+”

'); });
//服务对象--最初为空
var_services={};
$(“#serviceList输入[type=checkbox]”)。更改(函数serviceList()
{
//对于#serviceList容器中的每个复选框,请执行以下操作
$(this).each(function()
{
//将“_key”设置为复选框的id
var_key=(this).id;
//如果选中复选框--ADD--则将其键/值对添加到“services”对象中
//未选中else复选框--从“服务”对象中删除--键/值对
(this.checked)?\u services[\u key]=(this).value:delete\u services[\u key];
//console.log(_服务);
});//结束foreach()
//foreach services打印段落以显示键/值
$。每个(_服务、功能(索引、值)
{
$('#test').html(''+index+“:“+value+”

'); });//终端服务foreach }); // 结束服务列表()


如果正确理解了问题,这是因为每次都会覆盖
#test
元素的内容。附加以下内容如何:

   $('#test').append('<p>' +index+ ":" +value+ '</p>');
$('#test')。追加(''+index+“:“+value+”

');
每次写新行时,您都在清除容器的
innerHTML
。相反,您应该在
每个循环之前设置内容并清除容器:

$('#test').empty(); 
$.each(_services, function(index,value) {
    $('#test').append('<p>' +index+ ":" +value+ '</p>');
});
$('#test').empty();
$。每个(_服务、功能(索引、值){
$('#test')。追加(''+index+“:“+value+”

'); });
查看下面的演示:

var\u services={};
$(“#serviceList输入[type=checkbox]”)。更改(函数serviceList(){
//对于#serviceList容器中的每个复选框,请执行以下操作
$(此)。每个(函数(){
//如果选中复选框--ADD--则将其键/值对添加到“services”对象中
//未选中else复选框--从“服务”对象中删除--键/值对
this.checked?_服务[this.id]=this.value:删除_服务[this.id];
//console.log(_服务);
});//结束foreach()
//foreach services打印段落以显示键/值
$('#test').empty();
$。每个(_服务、功能(索引、值){
$('#test')。追加(''+index+“:“+value+”

'); }); }); // 结束服务列表()

  • 测试A
  • 测试B
  • 测试C
  • 测试D

我在发布之前尝试了追加,不幸的是,它会导致每次迭代都重复上一次。如果选中所有复选框,我将得到10个p标签checked@kash101您能否使用alert查看
索引
的值,如
警报(索引+”:“+值)是的,警报一次只运行一次。.append在循环处理该问题之前进行了清除。我发誓,很多时候都是一些微妙的事情悄悄地爬上来咬你的屁股谢谢,我从来没有想到过循环之前的.empty()。非常感谢。是的,您也可以出于同样的目的使用
.html(“”)