2010-11-13 76 views
1

我正在嘗試使用jQuery編寫自己的就地編輯。我的代碼是這樣的;使用jQuery編輯選擇新插入的元素

$(".comment-edit").bind({ 
    click: function(){ 
     commentId = $(this).parent().parent().attr("id"); 
     commentEditable = $("#"+commentId+" .comment-text"); 
     if (commentEditable.hasClass('active-inline')) { 
      alert("already editable aq"); 
      return false; 
     } 
     contents = $.trim($("#"+commentId+" .comment-text").text()); 
     commentEditable.addClass("active-inline").empty(); 
     var editBox = '<textarea id="newComment"cols="50" rows="6"></textarea><button class="newCommentSave">Save</button><button class="newCommentCancel">Cansel</button>'; 
     $(editBox+" textarea").val(contents).appendTo(commentEditable).focus(); 

     $.(".newCommentSave").live({ 
      click: function(){ 
       alert("Save"); 
       return false; 
      } 
     }); 

     $.(".newCommentCancel").click(function(){ 
      alert("Cancel"); 
      return false; 
     }); 
     return false; 
    } 
}); 

正如你所看到的,我嘗試了「live()」和「click()」來與新創建的按鈕進行交互。但是這不起作用。

我得到XML過濾器適用於非XML值(function (a, b) {return new (c.fn.init)(a, b);})

任何想法?什麼似乎出錯?

編輯: 的Html看起來是這樣的:

<div class="comment" id="comment-48"> 
    <div class="comment-author"> 
    <a href="/profil/defiant">defiant</a> 
    <span class="date">2010-11-09 01:51:09</span> 
    </div> 
    <div class="comment-text">Comment Text....</div> 
</div> 
+0

什麼是你的html樣子? – 2010-11-13 14:23:59

回答

1

事實證明,對於XML錯誤的原因是一個「」

$.(".newCommentSave").live({ 
// stuff 
}) 

美元符號後面的點是導致此錯誤的原因。至少代碼工作正常,沒有它。

0

我傾向於做這樣的事情(在我的例子,以一個跨度)附加click事件

var span = $("<span>some text</span>"); 
span.click(function() { alert('yay'); }); 

我會將你的editBox變量分解成三個不同的變量,然後看看會發生什麼。

0

.live()語法是.live('event', function),我不認爲它接受事件:函數對的映射。

所以會這樣的工作?

$.(".newCommentSave").live('click', function(){ 
    alert("Save"); 
    return false; 
}); 

我不知道爲什麼你的.click()處理程序不能正常工作。

+0

試過了。但仍然得到上面提到的XML過濾器錯誤。 – Sinan 2010-11-13 14:46:45

1

的問題是在這裏:

var editBox = '<textarea id="newComment"cols="50" rows="6"></textarea><button class="newCommentSave">Save</button><button class="newCommentCancel">Cancel</button>'; 
$(editBox+" textarea").val(contents).appendTo(commentEditable).focus(); 

editBox是一個字符串,所以你得到這個結果:

$("<textarea/><button /> textarea") 

...這不是XML或有效的選擇,拋出一個錯誤。相反,你要這樣:

$(editBox).filter("textarea").val(contents) 
      .end().appendTo(commentEditable).focus(); 

這會從您剛剛通過.filter()(因爲它是一個根級別元素)創建該對象的<textarea>,設置內容,然後使用.end()跳回到鏈$(editBox)包含兩個元素都要追加。這雖然焦點的按鈕,所以你可能想這個代替:

$(editBox).appendTo(commentEditable).filter("textarea").val(contents).focus(); 
+0

看來,原代碼莫名其妙的作品。它選擇並填充新創建的文本框。但是,您的代碼更符合您的解釋。謝謝! – Sinan 2010-11-13 15:27:49