2010-03-17 14 views
1

我是JQuery的新手,所以我很抱歉,如果有什麼應該是明顯的,我不知道。我似乎有幾個問題的一些JQuery的,我想實現:JQuery:動態生成的表單字段未提交,事件處理程序似乎多次觸發

代碼: http://pastebin.ca/1843496(編輯似乎並不喜歡HTML標籤)

<html> 
<head> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 

<script> 
$(document).ready(function() { 

var currentcontainer; 

$('a.edit').click(function() { 

currentcontainer = $(this).closest('div.container'); 

currentcontainer.prepend('<form action="post_test.php" method="POST"><input type="hidden" name="editing" value="1" /><input type="hidden" name="containerid" value="' + currentcontainer.attr('containerid') + '" />'); 

var old_title = currentcontainer.find('div.title_container>.editable').text(); 

currentcontainer.find('div.title_container>.editable').html('Title: <input type="text" name="new_title" value="' + old_title + '" />'); 

currentcontainer.append('</form>'); 

$(this).addClass('save'); 
$(this).text('Save'); 
$(this).removeClass('edit'); 

$('a.save').click(function() { 
currentcontainer.find('form').submit(); 
}); 

}); 

}); 
</script> 
</head> 
<body> 
<div class="container" containerid="1"> 

<div class="title_container"> 
<span class="editable"> 
Foo 
</span> 
</div> 

<div class="links"> 
<a class="edit" href="#">Edit</a> 
</div> 
</div> 
</body> 
</html> 

post_test.php只包含: [?php print_r($ _ POST); ?] 試圖找出實際提交的內容。

我遇到的第一個問題是隻有隱藏的表單字段實際上被提交。如果我手動將標籤插入到容器DIV中,它將按預期工作,但如果按上述方式完成,則不會發布文本字段。從我讀過的內容來看,我認爲這是因爲DOM在加載後被修改的事實,但令我困惑的是爲什麼在這種情況下,沒有任何問題引用其他添加的隱藏字段或標籤。我已經嘗試將a.save的事件處理程序更改爲'.live('click',function ...'以及使用LiveQuery無效。

另一個問題是,當單擊a.save時,在表單實際提交之前,據我所知,事件處理程序正在再次運行,用editable.text()的值替換輸入到文本字段中的值,最終得到提交的值。

我很抱歉,如果任何不清楚這個

問候,

+0

順便說一句,你可能想看看可調整的,看起來像你想做的事情相當不錯:http://www.appelsiini.net/projects/jeditable – 2010-03-17 12:45:59

回答

1

試試這個爲你的jQuery部分:

$(document).ready(function() {    
    $('a.edit').click(function() { 
    var con = $(this).closest('div.container'); 
    con.wrapInner('<form action="http://home.ncraver.com/test2.html" method="POST"></form>'); 
    con.find("form").append('<input type="hidden" name="editing" value="1" /><input type="hidden" name="containerid" value="' + con.attr('containerid') + '" />'); 

    con.find('div.title_container>.editable').each(function() { 
     $(this).html('Title: <input type="text" name="new_title" value="' + $(this).text() + '" />'); 
    }); 

    $(this).removeClass('edit').addClass('save').text('Save').unbind('click').click(function() { 
     con.find('form').submit(); 
    }); 
    }); 
}); 

變化:

  • .wrapInner() - 使用它來代替<form>然後</form>
  • .each() - 設定值
  • .unbind()的只是一個更合適的方法 - 從節約鏈接
  • 刪除事件處理程序

您的處理程序可執行因爲$('a.edit')表示「找到所有具有'編輯'類的元素」,並將這個事件處理程序綁定到他們。之後,處理程序在元素上......事實上,您刪除了編輯類並不意味着該處理程序已被刪除,它仍在元素上。我們通過調用.unbind('click')來解決此問題。

1

頁面加載後添加到表單中的事實不會阻止它被提交。使用Firebug將其加載到Firefox中,並在加載後檢查表單,確保所有內容都正確放置在表單內,並且標籤格式良好。

相關問題