开发者

function binding and the clone() function - Jquery

I have problems with my keyup binding when cloning an element. Here's the scenario:

I have an html markup like this:

<tr class="rijbasis">
   <td>
      <input type="text" class="count" />
   </td>
   <td>
       <span class="cost">10</span>
   </td>
   <td>
       <span class="total">10</span>
   </td>
</tr>

I'm binding an keyup function to the input element of my table row like this:

$('.rijbasis input').keyup(function(){
    var parent = $(this).parent().parent();
     $('.total',parent).text(parseInt开发者_如何转开发($('.cost',parent).text()) * parseInt($('.count',parent).val()));
}

I designed the function like this so I could clone the table row on a onclick event and append it to the tbody:

$('.lineadd').click(function(){
        $('.contract tbody').append($('.contract tbody tr:last').clone());
        $('.contract tbody tr:last input').val("0");
 });

This al works , but the keyup function doesnt work on the input elements of the cloned row..

Can anybody help or advice? I hope I was clear enough and I'll be surely adding details if needed to solve this problem.

Greetings


You've got two real options

  • use clone(true) which will also clone the bound event handlers
  • use event delegation with live() so that the event handler is bound to a parent element and thus newly added rows will get the same functionality


Use jQuery's live events; this way the handler will automatically be bound to newly created elements (such as the clones in your example).

For example:

$('.rijbasis input').live('keyup', function()
{
    var parent = $(this).parent().parent();
    $('.total',parent).text(parseInt($('.cost',parent).text()) * parseInt($('.count',parent).val()));
}


Use .live instead of .keyup

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜