JavaScript函数仅在删除时运行一次

时间:2019-05-23 12:51:35

标签: javascript jquery html

我有两个按钮,一个创建,一个删除不同的用途

<button id="create-user" class="btn btn-primary" style='float:right; margin-right: 230px;'>Add</button>

上面的按钮创建并且仅位于div中。没什么特别的。 但是,删除按钮是在下表中动态创建的。 函数查找正在使用在搜索URL中具有3种不同类型的ID的rest应用程序。该表已填充且数据正确。

<table id="users" class="table" align="center">
    <thead>
        <tr>
            <th>Name</th>
            <th>=ID</th>=
            <th>JSON Value</th>
            <th>placeholder for remove</th>
        </tr>
    </thead>
    <tbody>
        <?php
            for($i = 0; $i < 3; $i++){
                // lookup function to call rest API and existing gather data
                $json = lookup($name, $id[$i], "GET");
                if ($json["Value"] == "Y" || $json["Value"] == "N"){
                    $temp = $json["Value"];
                    echo "<tr id='$name'><td>$name</td><td>$id</td><td>$temp</td><td><button id='remove-user' class='btn btn-sm btn-primary'>Remove</button></td></tr>";
                }
            }
        ?>
    </tbody>
</table>

我的问题是,当我单击“删除”时,它会成功删除它(目前仅用rowid = 1进行测试。但是,当我添加时,它将添加到表和要搜索的ID列表中,它不想删除再次刷新。每次刷新一次只能工作一次。添加在删除操作不起作用的情况下一直起作用。

 <script>

    $( function() {
        var dialog, form,
        name = $( "#name" ),
        id = $( "#id" ),
        id_val = $( "#id_val" ),
        allFields = $( [] ).add( name ).add( id ).add( id_val );
        var current_IDS = getIDS();

        function getIDS(){
            // go through table and gather existing keys
            var table = document.getElementById("users");
            var IDS = [];
            var first_row = table.rows[1];
            var second_row = table.rows[2];
            var third_row = table.rows[3];
            if(typeof first_row.id !== 'undefined'){
                IDS.push(first_row.id);
            }
            if(typeof second_row !== 'undefined'){
                IDS.push(second_row.id);
            }
            if(typeof third_row !== 'undefined'){
                IDS.push(third_row.id);
            }
            return IDS;
        }

        // compare keys to make sure not adding duplicates
        function checkIDS(id){
            if(current_IDS[0] == id){
                return false;
            } else if(current_IDS[1] == id){
                return false;
            } else if(current_IDS[2] == id){
                return false;
            } else {
                return true;
            }

        }

        function addUser() {
            //make sure not duplicate
            var valid = checkIDS(id_val.val());
            if(valid) {
                current_IDS.push(id_val.val());
                $( "#users tbody" ).append( "<tr id="+name.val()+">" +
                "<td>" + name.val() + "</td>" +
                "<td>" + id.val() + "</td>" +
                "<td>" + id_val.val() + "</td>" +
                "<button id='remove-user' class='btn btn-sm btn-primary'>Remove</button></td>" +
                "</tr>" );
                dialog.dialog( "close" );
                // post and send to restapi.php rest call
                $.post("restapi.php", {
                    name: name.val(),
                    id: id.val(),
                    id_val: id_val.val()
                });
            } else{
                alert("id already exists!");
            }
            return valid;
        }

        function deleteRow(rowid){
            var rows = getIDS();
            var first_row = rows[0];
            var second_row = rows[1];
            var third_row = rows[2];
            // check row id to see if its in table
            if(rowid == first_row || rowid == second_row || rowid == third_row ) {
                var row = document.getElementById(rowid);
                row.parentNode.removeChild(row);
                // remove from list of current ids
                current_IDS.splice(current_IDS.indexOf(rowid), 1);
            }
        }
        dialog = $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 400,
            width: 350,
            modal: true,
            buttons: {
                "Create new id": addUser,
                Cancel: function() {
                    dialog.dialog( "close" );
                }
            },
            close: function() {
                form[ 0 ].reset();
                allFields.removeClass( "ui-state-error" );
            }
        });

        form = dialog.find( "form" ).on( "submit", function( event ) {
            event.preventDefault();
            addUser();
        });

        $( "#create-user" ).button().on( "click", function() {
            dialog.dialog( "open" );
        });

        $("#remove-user").button().on( "click", function() {
            deleteRow("testname"); //specifically target testname to see if i can keep adding/removing
        });
    });
</script>

我的问题是如何使我的删除工作始终如一,而不必不断刷新页面。

1 个答案:

答案 0 :(得分:2)

您必须使用event-deligation

所以改变

$("#remove-user").button()

$('table#users').on("click", "#remove-user", function()...

注意:简单地说,jquery默认情况下无法识别动态添加的内容。因此,要解决这些元素以执行某些操作,我们尝试使用当时已经存在的父元素的document加载/渲染。

重要提示: :多个相同的id是非常不好的编码做法,因此,在每个删除按钮上将id="remove-user"更改为class="remove-user",然后修改如下代码:-

$('table#users').on("click", ".remove-user", function()...

class代表一组元素,而id代表独特元素,同时通过javascript / jQuery执行任何类型的动作。

相关问题