簡體   English   中英

如何在javascript中單擊按鈕時刪除完整行?

[英]How to delete a complete row on button click in javascript?

我有一個html/php 代碼,如下所示。 下面的html/php代碼的工作方式是在添加行時,我們可以從每一行中選擇日期並保存它。

需要做兩件事。

  1. 單擊“刪除”按鈕時,它應該從JSON數組中刪除該值,因為保存表單后所有內容都從JSON 中提取。

  2. 此外,在單擊刪除按鈕時,它應該從 DOM 中刪除完整的行。

你應該給每個添加的行一個與其等級相對應的 id:

row.id=i.toString();

然后使用以下代碼刪除該行:

var row = document.getElementById(rowrankid);
row.parentNode.removeChild(row);

我已經使用您的示例為您准備了一個代碼示例,該示例完全符合您的要求。

它使用 javascript fetch post 請求發布到您提供的腳本,以刪除 dom 元素並更新 json 文件。

我稍微改變了你的一些路徑,所以你需要把它們改回來(添加到 ../feeds/ 父目錄中)

一旦用戶按下按鈕,頁面將重新加載,顯示從 json 文件加載的更新界面。

可以進行一些改進,例如 javascript 不會在重新加載之前檢查以確保請求成功,但由於輸入是日期選擇它應該沒問題。

<?php

if(file_exists('./ptp-ess_landing_house.json')){
    $data = json_decode(file_get_contents('./ptp-ess_landing_house.json'));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $_POST = json_decode(file_get_contents('php://input'), true);

    if(isset($_POST['requestType']) && in_array($_POST['requestType'], ['remove'])) {

        switch ($_POST['requestType']) {
            case 'remove' :
                    //Unset the values
                    unset($data->row_delete[$_POST['data'] -1]);
                    unset($data->house_sitting_date[$_POST['data'] -1]);

                    //We are reindexing the arrays as we have deleted some rows, note that we are using +1 array indexes
                    $data->row_delete = array_values($data->row_delete);
                    $data->house_sitting_date = array_values($data->house_sitting_date);

                    foreach($data->row_delete as $key=>$value) {
                        $data->row_delete[$key] = strval($key+1);
                    }

                    //Write the file back
                    $fp = fopen('./ptp-ess_landing_house.json', 'w');
                    fwrite($fp, json_encode($data));
                    fclose($fp);

                    header("HTTP/1.1 200 OK");
                    echo 'ok';
                    die;

                break;

            default:
        }

    }
}
?>
<script>
    function rowDelete(row) {
        //Make a request to your entry file (index.php here) to do the removal
        fetch('/index.php', {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({requestType: 'remove', data: row})
        }).then(function(response) {
            location.reload();
            return response;
        });
    }
</script>
<?php if($data) { ?>
    <form method="post">
        <div id="rows" style="display:flex; justify-content: center;"><!-- Big div START -->

            <!-- Remove Button START -->
            <div class="rows-delete">
                <h4 style="text-align:center;">Delete Rows</h4>
                <?php if (empty($data->row_delete)) { ?>
                    <div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
                        <button type="button" id="delete" onclick="rowDelete()">Remove</button>
                        <input type="hidden" name="row_delete[]" value="1" />
                    </div>
                <?php } else {  ?>
                    <?php  foreach ($data->row_delete as $row_delete){ ?>
                        <div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
                            <button id="delete" type="button"  onclick="rowDelete(<?php echo $row_delete;?>)">Remove</button>
                            <input type="hidden" name="row_delete[]" value="<?php echo $row_delete;?>" />
                        </div>
                    <?php }} ?>
            </div>
            <!-- Remove Button END -->

            <!-- Sitting Date START -->
            <div class="sitting-days">
                <h4 style="text-align:center;">Select Date</h4>
                <?php if (empty($data->house_sitting_date)) { ?>
                    <!-- Select Date START -->
                    <div class="select-date" style="margin-right:30px; margin-top:20px;">
                        <input type="date" class="house-sitting-date" name="house_sitting_date[]" value="">
                    </div>
                <?php } else {  ?>
                    <?php  foreach ($data->house_sitting_date as $date){ ?>
                        <!-- Select Date START -->
                        <div class="select-date" style="margin-right:30px; margin-top:20px;">
                            <input type="date" class="house-sitting-date" name="house_sitting_date[]" value="<?php if($date) {echo $date;}?>">
                        </div>
                        <!-- Select Date END -->
                    <?php }} ?>
            </div>
            <!-- Sitting Date END -->

        </div><!-- Big div END -->
    </form>
<?php } else {
    echo 'Cannot read JSON settings file';
}
?>

如果您的 json 在前端是已知的(我認為您是在暗示,因為您的rowDelete是一個 JS 函數),您可以通過調用rowDelete來傳遞this 然后您可以遍歷 DOM 以獲取相應的兄弟輸入字段的值(可能類似於this.parentNode.childNodes[1] )。

獲得該值后,您可以輕松地將其從 json 中的對應數組中刪除:

let d = '2020-01-30'
let idx = arr.indexOf(d)   
let newdates = ([...arr.slice(0,idx), ...arr.slice(idx+1)])
data.house_sitting_date = newdates

(當然還有一些額外的索引邊界檢查)。

之后,您可以執行類似的 DOM 遍歷以從 DOM 中刪除相應的元素。

Flash,不幸的是,代碼本身的設計並不是很專業……行有單獨的循環(在 php 中),而應該只有 1 個循環,例如(單擊簡單的 Javascript 綁定示例):

<?php
for ($i=0; $i<count($data["house_sitting_date"]); $i++)
{
     echo '<div class="remove"><a id="'.$data["row_delete"][$i].'" onclick="deleteRow(this);">Remove</a></div>';
     echo '<div class="date">....</div>';
     ...
}
?>
<script> function deleteRow(el) { el.remove(); } </script>

此外,許多嵌入式style="" .. 代碼,而您可能會使用 1 個樣式文件。

這就是我過去所做的,而且效果很好

這個答案工作的先決條件是每個按鈕和輸入字段都應該在具有唯一 ID 的 DIV 中,並且在我的情況下應該有所有這些 div 的容器

.

在“添加”按鈕(如果有)上,您需要克隆節點,並將其粘貼到單擊它的元素下方或上方,

    // Create a clone of element with id ddl_1:
    let clone = document.querySelector('#row'+rownumber).cloneNode( true );
    // Append the newly created element on element p 
    document.querySelector('p').appendChild( clone );

然后,每次添加新行或刪除行時,您都需要在這些行上附加 id,為此,在我使用的情況下,您將為所有這些行創建一個公共類,行

    function changeids()
    {
     let rows =document.getElementsByClassName('rows');

     for(let i=0; i<rows.length; i++)
     {
       let thisid="row"+i;
       rows[i].setAttribute("id", thisid);

       let thisAddButton = rows[i].getElementsByClassName("add")[0];
       let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];

       let onclickaddfunction = "addrow("+i+")";
       thisAddButton.setAttribute("onclick", onclickaddfunction);

       let onclickDeletefunction = "removerow("+i+")";
       thisDeleteButton.setAttribute("onclick", onclickDeletefunction);

     }
}

然后當您刪除時,您需要刪除節點並再次調用 changeids

function removerow(rownumber){

document.getElementById('row'+rownumber).remove();
changeids();
}

這會給你添加和刪除行的完整工作想法,下面的整個代碼請忽略我凌亂的代碼,只是為了給你和想法

<p>

  <div id="row1" class="rows">
   <button class="add" onclick="addrow(1)">add</button>
   <button class="delete" onclick="removerow(1)"> remove </button>
   <input type="text">
  </div>
</p>


<script>
function addrow(rownumber)
{
  // Create a clone of element with id ddl_1:
  let clone = document.querySelector('#row'+rownumber).cloneNode( true );

 // Append the newly created element on element p 
 document.querySelector('p').appendChild( clone );

 changeids();

}

function removerow(rownumber)
{
   document.getElementById('row'+rownumber).remove();
   changeids();
}

function changeids()
{
  let rows =document.getElementsByClassName('rows')

  for(let i=0; i<rows.length; i++)
  {
   let thisid="row"+i;
   rows[i].setAttribute("id", thisid);

   let thisAddButton = rows[i].getElementsByClassName("add")[0];
   let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];

   let onclickaddfunction = "addrow("+i+")";
   thisAddButton.setAttribute("onclick", onclickaddfunction);

   let onclickDeletefunction = "removerow("+i+")";
   thisDeleteButton.setAttribute("onclick", onclickDeletefunction);

  }
}
</script>

要從 dom 中刪除行,您必須為行的主要元素指定唯一 id,您可以使用 [ElementObject].remove() 方法進行刪除,因此里面的所有內容都將被刪除。 此外,您應該簡化和更改 JSON 數據,以便它也使用 ajax 從 json 中刪除,並使用單個 id(key) 作為參數。

這是工作代碼:

<?php

        if (!empty($_GET)) {
            if (!empty($_GET['action']) && $_GET['action'] == 'delete') {
                if(file_exists('ptp-ess_landing_house.json')) {
                    $data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
                    if (!empty($_GET['row_number'])) {
                        unset($data[$_GET['row_number']]);

                        $fp = fopen('ptp-ess_landing_house.json', 'w');
                        fwrite($fp, json_encode($data));
                        fclose($fp);

                        echo 1;
                        exit;
                    }
                }

                echo 0;
                exit;
            }
        }

        if (!empty($_POST)) {
            $output = array();     

            if (!empty($_POST['row_item'])) {
                $output = $_POST['row_item'];
            }

            $fp = fopen('ptp-ess_landing_house.json', 'w');
            fwrite($fp, json_encode($output));
            fclose($fp);
        }

        $data = array();
        if(file_exists('ptp-ess_landing_house.json')) {
            $data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
        }

        ?><form method="post">
            <!-- Add New Row Button START -->
            <div class="plus-minus-button" style="text-align:center;">    
                <button type="button" id="addRow" onclick="rowAdd()">+</button>
            </div>

            <!-- Add New Row Button END -->
            <div id="maindiv">
                <div style="display:flex; justify-content: center;">
                    <div class="rows-delete" style="text-align:center;">
                        <div class="row-delete" style="margin-right:30px;">
                            <h4 style="text-align:center;">Delete Rows</h4>
                        </div>
                    </div>
                    <div class="sitting-days" style="text-align:center;">
                        <div class="select-date" style="margin-right:30px;">
                            <h4 style="text-align:center;">Select Date</h4>
                        </div>
                    </div>
                    <div class="choose-options" style="text-align:center;">
                        <div class="yes-no-option" style="display:inline-grid;">
                            <h4 style="text-align:center;">Yes/No</h4>
                        </div>
                    </div>
                </div>

                <!-- Big div START --><?php

                $totalrow = 0;
                foreach ($data AS $key => $row) {
                    ?><div id="row-<?php echo $key; ?>" style="display:flex; justify-content: center; margin-top:20px;"><?php

                        ?><div class="rows-delete" style="text-align:center;">
                            <div class="row-delete" style="margin-right:30px;">
                                <button type="button" class="delete" onClick="delete_row(this.value)" value="<?php echo $key; ?>">Remove</button>
                                <input type="hidden" name="row_item[<?php echo $key; ?>][row_delete]" value="<?php echo $row['row_delete'];?>" />
                            </div>
                        </div>  

                        <!-- Remove Button END -->
                        <!-- This is what I have tried to add a button (END) -->    

                        <!-- Sitting Date START -->
                        <div class="sitting-days" style="text-align:center;">
                            <div class="select-date" style="margin-right:30px;">
                                <input type="date" class="house-sitting-date" name="row_item[<?php echo $key; ?>][house_sitting_date]" value="<?php echo $row['house_sitting_date']; ?>">
                            </div>
                        </div>  
                        <!-- Sitting Date END -->

                        <!-- YES/NO START --><?php
                        ?><div class="choose-options">
                            <div class="yes-no-option" style="display:inline-grid;">
                                <select name="row_item[<?php echo $key; ?>][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
                                   <option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "nada" ) echo "selected";?>>Please choose an option</option>
                                   <option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "yes" ) echo "selected";?>>Yes</option>
                                   <option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "no" ) echo "selected";?>>No</option>
                                </select>
                            </div>
                        </div>
                        <!-- YES/NO END -->
                    </div><?php

                    if ($key > $totalrow) $totalrow = $key;
                    else $totalrow++;
                }
            ?>
            <input type="hidden" name="totalrow" id="totalrow" value="<?php echo $totalrow; ?>">
            </div>
            <!-- Big div END -->

            <hr />
            <div style="text-align:center;">
                <input type="submit" value="submit" />
            </div>

        </form>

        <script>
            function delete_row(row_number) {
                var data = '<?php echo json_encode($data) ?>';
                data = JSON.parse(data);
                if (typeof(data[row_number]) != undefined) {
                    var request = new XMLHttpRequest();
                    request.open("GET", "index.php?action=delete&row_number=" + row_number);
                    request.onreadystatechange = function() {
                        if (this.readyState === 4 && this.status === 200) {
                            var row = document.getElementById('row-'+row_number);
                            row.remove();
                        }
                    }
                    request.send();
                }
                else {
                    var row = document.getElementById('row-'+row_number);
                    row.remove();
                }
            }
            function rowAdd(event) {    
                var totalrow = document.getElementById("totalrow").value;
                totalrow = parseInt(totalrow) + 1;

                document.getElementById("maindiv").insertAdjacentHTML('beforeend', newRow(totalrow));

                document.getElementById("totalrow").value = totalrow;
            }
            function newRow(row_number) {
                return `<div id="row-` + row_number + `" class="sitting-days" style="display:flex; justify-content:center; margin-top:20px;">
                    <div class="rows-delete" style="text-align:center;">
                        <div class="row-delete" style="margin-right:30px;">
                            <button type="button"  class="delete" onClick="delete_row(this.value)" value="` + row_number + `">Remove</button>
                            <input type="hidden" name="row_item[` + row_number + `][row_delete]" value="` + row_number + `" />
                        </div>
                    </div>
                    <div class="sitting-days" style="text-align:center;">
                        <div class="select-date" style="margin-right:30px;">
                            <input type="date" class="house-sitting-date" name="row_item[` + row_number + `][house_sitting_date]" value="">
                        </div>
                    </div>
                    <div class="choose-options">
                        <div class="yes-no-option" style="display:inline-grid;">
                            <select name="row_item[` + row_number + `][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
                               <option value="nada">Please choose an option</option>
                               <option value="yes">Yes</option>
                               <option value="no">No</option>
                            </select>
                        </div>
                    </div>
                </div>`;
            }


    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM