如何在jquery中更新'onclick'事件?

时间:2012-02-24 21:59:48

标签: jquery

我有一个JSFiddle似乎应该有效,但事实并非如此。

function copyform(curnum){
    if(curnum == 3) $('p').html('Thank You!')
    var num = $('form').length;
    var newNum  = new Number(num + 1);

    // create the new element via clone(), and manipulate its ID using newNum value
    var newElem = $('#form'+curnum).clone().attr('id', 'form' + newNum);

    //
    //this is where I need to update the onclick to copyform('+newNum+')
    $('#form'+newNum+' input').attr('onclick', 'copyform('+newNum+')');

    // insert the new element after the last "duplicatable" input field
    $('form').after(newElem);

}

我只需要帮助实现onclick功能。这是一个更大的更复杂的程序的一部分,这将是一个难以展示的例子。非常感谢任何和所有帮助!

1 个答案:

答案 0 :(得分:0)

我改变了你的功能:

http://jsfiddle.net/yjAeS/3/

function copyform( curnum ){
  var curnum = + $(this).closest('[data-num]').attr('data-num');

    // put the message into current form's <p> only
  if( curnum == 3) $('#form'+curnum+' p').html('Thank You!')

  // let's put the last form into a variable for cloning and appending
  var $lastForm = $('#form'+curnum);

  var newNum = 1 + $('form').length; // number+string => number
  var $newElem = $lastForm.clone().attr({
    'id': 'form'+newNum,
    'data-num': newNum   // store the form number in a custom attribute
  });

  $lastForm.after( $newElem );
}

$(function(){
  // we don't have to attach event manually to each cloned form
  // http://api.jquery.com/on/
  $('body').on('click','form input[type="button"]', copyform );
});
​