开发者

Enabling live event after it has died

This is a continuation from the previous stackoverflow jQuery question I asked, but I don't think the line that says:

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

is working.

<!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">
&l开发者_开发问答t;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>

I want the user to be able to add a new row, but not click "Add" over and over again continually.

With your help, I've disabled the "Add" event, but now I'm having trouble getting back enabled.


don't die, have some variable to tell if insert is locked;

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
}


insertHandler expects a table row as a parameter. When you re-attach it that way, it will pass the TD as a parameter.

Also, why do you need live()? There is a bit of performance overhead involved with event delegation. It is not advised unless you need to attach a handler to multiple elements or elements created in future dynamically. So it makes sense for $('input[name="myid"]').live('focusout',... but not for Add, Delete.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜