javascript - 简单的 JavaScript 和 jQuery 函数 'Sometimes' 运行太多次

标签 javascript jquery

我构建了一个演示,它仅允许您创建新行并删除它们。这些行被赋予一个唯一的 data-id 属性和一个对象,其中每个 data-id 都被推送到 rows 数组中。

出于某种原因,单击“删除行”图标有时会多次尝试将其删除 - 例如,执行以下操作:

打开 JS 控制台,添加 2 行(通过单击“添加一行”两次),然后删除中间行号 2(通过单击该行左侧的删除图标),您将看到控制台记录“已删除行 2”两次 - 它应该只记录一次。如果您创建大量行然后删除行,有时会多次重复该操作。

有谁知道为什么会发生这种情况以及如何解决?我很困惑。它应该只发生一次,并且我假设整个函数运行了很多次。任何修复和“最佳实践”建议都会非常有帮助,谢谢。

代码笔:https://codepen.io/anon/pen/drWyQb

let templateRow, addBtn, templateRows, tableBody, popup, objects, rows = [];

$(document).ready(function(){
    runDefaults();
});

function runDefaults() {
    $(".no_entries_row").detach().insertBefore(".template_row");
    $('.template_row').first().attr('data-id', '1');
    defineVariables();
    removeRow();
    testEmpty();
    showSuccess();
    addRow();
    changeBg();
}

function defineVariables() {
    templateRow = $('<div>').append($('.template_row').clone()).html();
    addBtn = $('.list_add');
    templateRows = $('.template_row');
    popup = $(".popup");
    tableBody = $('tbody');
}

function removeRow() {
    let removeId;
    
    // REPEATING ERROR SOMEWHERE HERE?
    templateRows.on("click", ".controls", function(){
        removeId = $(this).parent().attr('data-id');
        $(this).parent().fadeOut(0, function(){
            $(this).remove();
        });
        templateRows = $('.template_row');
        testEmpty();
        rows = rows.filter(obj => obj.id != removeId); console.log('Removed Row ' + removeId);
    });
}

function testEmpty() {
    let rowsLen = $('.template_row').length,
        noEntriesRow = $('.no_entries_row');
    if (rowsLen === 0)
        noEntriesRow.css('display','table-row');
    else
        noEntriesRow.css('display','none');
}
    
function showSuccess() {
    $(".submit").click(function(){
        popup.fadeIn();
    });
}

function addRow() {
    let id = 1;
    new rowObj(1);
    
    addBtn.on("click", function(){        
        id++;
        tableBody.append(templateRow);
        templateRows = $('.template_row');
        noOfRows = templateRows.length;
        $('.template_row:nth-of-type(' + (noOfRows+1) + ')').attr('data-id', id);
        removeRow();
        testEmpty();
        changeBg();
        new rowObj(id);
    });
}

function changeBg() {
    $(".label").change(function () {
    let colour = this.value;
        $(this).parent().parent().css('background', colour);
    });
}

function rowObj(id) {
    this.id = id;
    this.description = 'Table Row';
    
    rows.push(this);
}
* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}
body {
    padding: 30px;
    font-family: arial;
}
table {
    width: 100%;
    background-color: #fff;
    text-align: left;
    border: 1px solid #ccc;
    border-collapse: collapse;
    margin-bottom: 10px;
}
tbody tr:not(:last-of-type), thead tr { border-bottom: 1px solid #ccc }
thead th {
    background: #f0f0f0;
    padding: 10px;
}
td { padding: 10px 10px 10px 0 }
.no_entries_row > td { padding-left: 60px }
.btn_col, .controls { text-align: center }
.controls { padding: 0 }
a.list_cancel { color: #000 }
a.list_add {
    text-decoration: none;
    color: #54A2CE;
}
i[class*="fa fa-plus-square"] { color: #999999 }
.action_btn {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    width: auto;
    justify-content: center;
    margin-top: 20px;
}
.action_btn input { margin: 0 }
input[name~="submit"] {
    padding: 5px 15px;
    font-size: 1em;
    margin: 0 10px;
}
.popup {
    flex: 1 100%;
    margin-top: 30px;
    text-align: center;
    font-size: 1.5em;
    display: none;
}
.popup > p {
    padding: 20px 50px;
    background: lightgreen;
    font-weight: 700;
    border-radius: 15px;
}
@media (min-width: 950px) {
   .popup > p {
       width: 25%;
       margin: 0 auto;
    } 
}
input, select {
    width: 100%;
    border-radius: 5px;
    padding: 5px;
    border: 1px solid #ccc;
}
select {
    -webkit-appearance: menulist-button;
    -moz-appearance: menulist-button;
    appearance: menulist-button;
    padding: 5px;
    height: 25px;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>     
</head>

<body>

<div class="wrapper">
	
            <table class="common_table" cellspacing="0">
          
            <thead>
            <tr>
                <th class="btn_col"></th>
            	<th class="code_col">Demo Column 1</th>
            	<th>Demo Column 2</th>
            	<th class="data_col">Demo Column 3</th>
            	<th class="data_col">Demo Column 4</th>
            	<th class="short_col">Col 5</th>
            	<th class="data_col">Demo Column 6</th>
            </tr>
            </thead>
            <tbody>
            
            <tr class="template_row">
            	<td class="controls"><a href="#" class="list_cancel" title="Delete Row"><i class="fa fa-minus-circle"></i></a></td>
                <td><input type="text" class="" id="productcode" name="" value=""/></td>
                <td><input type="text" class="long" id="productname" name="" value=""/></td>
                <td><input type="text" class="" id="stock" name="" value=""/></td>
                <td><input type="text" class="" id="vendor" name="" value=""/></td>
                <td>
                    <select name="" id="" class="label">
                        <option value = ""></option>
                        <option value = "green" style="background-color:green;">Success</option>
                        <option value = "red" style="background-color:red;">Wrong</option>
                        <option value = "orange" style="background-color:orange;">Error</option>
                    </select>
                </td>
                <td><input type="text" class="" id="client" name="" value=""/></td>
            </tr>
			<tr class="no_entries_row">
            	<td colspan="7">No Entries</td>
            </tr>

            </tbody>
            </table>
            
        	<a href="#" class="list_add"><i class="fa fa-plus-square"></i> Add one row</a>
            
            <br class="clear" />
            
            <div class="action_btn">
                <input name="submit" class="action_btn submit" type="submit" value="Save"/>
                <input name="submit" class="action_btn cancel" type="submit" value="Cancel"/>
                <div class="popup">
                    <p>Saved successfully!</p>
                </div>
            </div>
             
        </div>
        
</body>
</html>

最佳答案

以我的拙见,您的代码太复杂

下面是相同的行添加/删除行为没有您的实际问题以及基于 <select> 的行着色改变...只有 3 个事件处理程序。

我没有碰你的 HTML 标记。我添加了一条 CSS 规则(以隐藏模板行)...并从头开始完全重写代码。

随意提问,因为可能有很多事情需要解释。 ;)

我认为,关键是我更关注用户触发的事件,而不是“子功能命名”。结果是 28 行与 84 行...

$(document).ready(function(){
  
  var table_body = $(".common_table tbody");
  
  // "Add one row" link
  $(".list_add").on("click",function(){
    console.log("Added a row");
    $(".no_entries_row").hide();
    var clone = $(".template_row").clone().removeClass("template_row");
    table_body.append(clone);
  });
  
  // Remove row icon
  $(document).on("click",".list_cancel",function(){
    console.log("Removed a row");
    $(this).closest("tr").remove();
    if(table_body.find("tr:visible").length==0){
      console.log("No more row!");
      $(".no_entries_row").show();
    }
  });
  
  // Select "success/wrong/error"
  $(document).on("change",".label",function(){
    console.log("Changed color");
    $(this).closest("tr").css({"background-color":$(this).val()});
  });
});  // End ready
* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}
body {
    padding: 30px;
    font-family: arial;
}
table {
    width: 100%;
    background-color: #fff;
    text-align: left;
    border: 1px solid #ccc;
    border-collapse: collapse;
    margin-bottom: 10px;
}
tbody tr:not(:last-of-type), thead tr { border-bottom: 1px solid #ccc }
thead th {
    background: #f0f0f0;
    padding: 10px;
}
td { padding: 10px 10px 10px 0 }
.no_entries_row > td { padding-left: 60px }
.btn_col, .controls { text-align: center }
.controls { padding: 0 }
a.list_cancel { color: #000 }
a.list_add {
    text-decoration: none;
    color: #54A2CE;
}
i[class*="fa fa-plus-square"] { color: #999999 }
.action_btn {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    width: auto;
    justify-content: center;
    margin-top: 20px;
}
.action_btn input { margin: 0 }
input[name~="submit"] {
    padding: 5px 15px;
    font-size: 1em;
    margin: 0 10px;
}
.popup {
    flex: 1 100%;
    margin-top: 30px;
    text-align: center;
    font-size: 1.5em;
    display: none;
}
.popup > p {
    padding: 20px 50px;
    background: lightgreen;
    font-weight: 700;
    border-radius: 15px;
}
@media (min-width: 950px) {
   .popup > p {
       width: 25%;
       margin: 0 auto;
    } 
}
input, select {
    width: 100%;
    border-radius: 5px;
    padding: 5px;
    border: 1px solid #ccc;
}
select {
    -webkit-appearance: menulist-button;
    -moz-appearance: menulist-button;
    appearance: menulist-button;
    padding: 5px;
    height: 25px;
}

/* ============ ADDED =========== */
.template_row{
  display:none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">

  <table class="common_table" cellspacing="0">

    <thead>
      <tr>
        <th class="btn_col"></th>
        <th class="code_col">Demo Column 1</th>
        <th>Demo Column 2</th>
        <th class="data_col">Demo Column 3</th>
        <th class="data_col">Demo Column 4</th>
        <th class="short_col">Col 5</th>
        <th class="data_col">Demo Column 6</th>
      </tr>
    </thead>
    <tbody>

      <tr class="template_row">
        <td class="controls"><a href="#" class="list_cancel" title="Delete Row"><i class="fa fa-minus-circle"></i></a></td>
        <td><input type="text" class="" id="productcode" name="" value="" /></td>
        <td><input type="text" class="long" id="productname" name="" value="" /></td>
        <td><input type="text" class="" id="stock" name="" value="" /></td>
        <td><input type="text" class="" id="vendor" name="" value="" /></td>
        <td>
          <select name="" id="" class="label">
            <option value=""></option>
            <option value="green" style="background-color:green;">Success</option>
            <option value="red" style="background-color:red;">Wrong</option>
            <option value="orange" style="background-color:orange;">Error</option>
          </select>
        </td>
        <td><input type="text" class="" id="client" name="" value="" /></td>
      </tr>
      <tr class="no_entries_row">
        <td colspan="7">No Entries</td>
      </tr>

    </tbody>
  </table>

  <a href="#" class="list_add"><i class="fa fa-plus-square"></i> Add one row</a>

  <br class="clear" />

  <div class="action_btn">
    <input name="submit" class="action_btn submit" type="submit" value="Save" />
    <input name="submit" class="action_btn cancel" type="submit" value="Cancel" />
    <div class="popup">
      <p>Saved successfully!</p>
    </div>
  </div>

</div>

CodePen

关于javascript - 简单的 JavaScript 和 jQuery 函数 'Sometimes' 运行太多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55053760/

相关文章:

javascript - 函数 "select all"和iCheck

javascript - 在 JSFiddle 中加载 Facebook API

javascript - 单击按钮时 knockout 更改跨度可见状态

javascript - 我应该向这个 JavaScript 函数传递什么参数?

JQuery 记住 CSS 布局更改?

javascript - 'live'元素的解释

javascript - Bootstrap 3 - 折叠时自定义导航栏相对于品牌/ Logo 的位置

Jquery,获取元素在溢出内的位置:hidden

jquery - 拖放 div 并存储位置

javascript - 缩小粘性导航栏