死亡后启用直播活动

时间:2010-02-24 21:10:18

标签: jquery

这是我之前提到的stackoverflow jQuery问题的延续,但我不认为该行说:

$(".insert").live("click", insertHandler);

正在运作。

<!DOCTYPE HTML>
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function insertHandler(currentRow) {
    var newRow = currentRow.clone(true);
    newRow.children('td:last').empty().append('<input name="myid" />');
    currentRow.after(newRow);
    document.myForm.myid.focus();
}

function OnLoad() {
    $('input[name="myid"]').live('focusout', function() {
        var myValue = $(this).val();
        var currentCell = $(this).parents("td");
        currentCell.empty().append(myValue);
        $(".insert").live("click", insertHandler); // I need help here
    });
    $('.insert').live('click', function() {
        $('.insert').die();
        var currentRow = $(this).parents("tr:first");
        insertHandler(currentRow);
    });
    $('.delete').live('click', function() {
        if (confirm("Are you sure?")) {
            $(this).parents("tr").remove();
        }
    });
}
google.load("jquery", "1");
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body>
<form name="myForm">
<table border="1">
<tr>
<td class="insert">Add</td>
<td class="delete">Erase</td>
<td>Sample data goes here</td>
</tr>
</table>
<input name="Other">
</form>
</body>
</html>

我希望用户能够添加新行,但不要一遍又一遍地点击“添加”。

在您的帮助下,我已禁用“添加”活动,但现在我无法恢复启用。

2 个答案:

答案 0 :(得分:1)

insertHandler期望将表格行作为参数。当您以这种方式重新附加时,它会将TD作为参数传递。

另外,为什么需要live()?事件委派涉及一些性能开销。除非您需要将处理程序附加到将来动态创建的多个元素或元素,否则不建议使用它。所以它对$('input[name="myid"]').live('focusout',...有意义,但不适用于Add,Delete。

答案 1 :(得分:1)

不要die,有一些变量来判断插入是否已被锁定;

var insertlocked = false;

$('.insert').live('click', function() {
        if (insertlocked){ return; } //if insert is locked, don't do nothing
        insertlocked = true; //lock insert
        //$('.insert').die(); - don't use this
        var currentRow = $(this).parents("tr:first");
        insertHandler(currentRow);
    });

function insertHandler(...){
  ...
  document.myForm.myid.focus();
  insertlocked = false; //unlock insert again
}
相关问题