e.preventDefault()不起作用

时间:2013-09-15 22:21:36

标签: javascript jquery html

我有一个表,其中的行是通过元素的单击事件生成的。现在,这完全有效,问题在于删除部分。例如,我已经添加了5行,当我单击删除按钮(删除按钮也是通过jQuery也在addRow()click事件上创建)时,通过jQuery函数添加的所有行都被删除,表单提交事件虽然我有一个名为。

的e.preventDefault()方法

JavaScript / jQuery代码:

        var counter = 2;            
        window.addRow = function addRow() {
            var newRow = $('<tr><td><label>'+ counter +'</label></td><td><textarea name="txtActionStep' + counter + '" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td><td valign="top"><input type="text" name="txtOwner' + counter + '"/></td><td><button class="delete">delete</button></td></tr>');
            counter++;                
            $('table.actionsteps-list').append( newRow );
        }

        $('table.actionsteps-list').on('click', '.delete', function(e){ 
          e.preventDefault(); // stops the page jumping to the top
          $(this).closest('tr').remove();
        });


        function postForm() {
            var form = document.getElementById('actionStepsForm');
            document.getElementById('rowCount').value = counter-1;
            form.submit();
        }

HTML代码(表单本身):

<form name="actionStepsForm" id="actionStepsForm" action="add_reprocessing.php?action=add" method="post">
<table class="actionsteps-list" width="510">
        <tr>
            <th colspan="3" align="left">Action Steps</th>
        </tr>
        <tr>
            <td>Step #</td><td>Action Step</td><td>Owner</td>
        </tr>
        <tr>
            <td>
                <label>1</label>
            </td>
            <td>
                <textarea name="txtActionStep1" style="width:300px; height: 50px; word-wrap:break-word;"></textarea>
            </td>
            <td valign="top">
                <input type="text" name="txtOwner1" />
            </td>
        </tr>
    </table>
    <table width="510">
        <tr>
            <td align="right"><a href="#" title="" onclick="addRow(); return false;">Add Action</a></td>
        </tr>
    </table>
    <input type="button" value="Create" onclick="postForm(); return false;" />
<input type="hidden" value="" id="rowCount" name="rowCount" />
</form>

信不信由你,我已经被困在这里将近3天了。我在网上找不到任何修复方法。我没错。

1 个答案:

答案 0 :(得分:1)

 $('table.actionsteps-list').on('click', '.delete', function(e){ 
      e.preventDefault(); // stops the page jumping to the top
      $(this).closest('tr').remove();
    });

$(function(){$('table.actionsteps-list').on('click', '.delete', function(e){ 
      e.preventDefault(); // stops the page jumping to the top
      $(this).closest('tr').remove();
    });
 )};