javascript - jQuery 如何在循环中仅追加一次数据

标签 javascript jquery html

我使用循环,并通过按钮将数据添加到表中。 因此,每次它都会为我创建 5 个单元格,但我只需在单击按钮后追加一次数据。

代码:

$('.next').on('click', function () {
    $('.changeoverTable').show();
    var arrNumber = new Array();
    $('input[type=text]').each(function (i) {
        arrNumber.push($(this).val());
            $(".changeoverTable > tbody").append('<tr><td>Data</td><td>' + arrNumber[i] + '</td></tr>'); 
    })
});
body {
  background: #f5f5f5;
}

.hide {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" placeholder="Enter number of data"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
<input type="text" placeholder="Enter number of nest"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
   <table class="changeoverTable hide">
                <thead>
                    <tr>
                        <th colspan="3">Table</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>

如您所见,每次单击“确定”后,我都会得到 5 行,但我只需要每个输入字段中的一行。

最佳答案

只需执行 if 条件 if(arrNumber[i]){ 检查值是否存在。

$('.next').on('click', function () {
    $('.changeoverTable').show();
    var arrNumber = new Array();
    $(".changeoverTable > tbody").html('');
    $('input[type=text]').each(function (i) {
    
        arrNumber.push($(this).val());
        if(arrNumber[i]){
            $(".changeoverTable > tbody").append('<tr><td>Data</td><td>' + arrNumber[i] + '</td></tr>'); 
            }
    })
});
body {
  background: #f5f5f5;
}

.hide {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" placeholder="Enter number of data"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
<input type="text" placeholder="Enter number of nest"><button class="next">ok</button>
<input type="text" placeholder="Enter number of layers"><button class="next">ok</button>
   <table class="changeoverTable hide">
                <thead>
                    <tr>
                        <th colspan="3">Table</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>

关于javascript - jQuery 如何在循环中仅追加一次数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56107670/

相关文章:

javascript - 如果元素为空隐藏下一个元素

javascript - jquery 下拉列表

jquery - 使用 jQuery 数据表插件的服务器端分页

html - 我可以在 GitLab 上渲染 HTML 吗?

html - 加载页面上的 CSS3 字母间距动画

javascript - 编辑值时输入失去焦点。使用 ngFor 和 ngModel。 Angular 5

javascript - 上传 Node FS 后文件损坏

javascript - 如果我的用户有 ie6 该怎么办

javascript - 如何从注册页面进入预览页面并从预览页面返回注册页面进行修改

javascript - 高阶 reduce() 函数