2013-05-09 55 views
5

http://jsfiddle.net/YsnhT/2/jquery事件追加後不工作

jquery event on append後不工作。點擊保存按鈕後,我需要textarea的值。

$('.span8') 
    .on('click', 
      '.btn', 
      function() { 
     var input = $("#textarea").val(); 
     alert(input); 
    }); 

$('body').on('click','#createNote',function() {    $('.span8').empty(); 
       $('.span8').append('<button type="button" class="btn" style="float: right; margin-right: 8px;background-color:#dddddd;font-family:Roboto Slab;color: black" id="save" data-loading-text="Saving...">Save</button><div class="hero-unit"><input type="text" style="width: 100%" id="title" placeholder="Title"/>'+ 
       '<textarea contenteditable="true" id="textarea" class="textarea" placeholder="Enter text ..."style="width: 100%;">dd</textarea></div>'); 

      }); 

HTML:

<div class="span8"></div> 
+0

[動態生成的元素觸發的事件不會被事件處理程序捕獲]的可能重複(http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured由事件手) – 2014-03-02 19:17:38

回答

14

由於#save是動態創建的,請使用以下處理:

$(document).on('click', '#save' ,function() { 
    //do stuff 
}); 

更新小提琴:http://jsfiddle.net/tymeJV/YsnhT/3/

你也應該讓你的 「點擊」像這樣的按鈕處理程序,否則它不會觸發新的c重新編號爲#click按鈕。

+0

非常感謝,它像一個魅力。 – shashank 2013-05-09 13:16:08

1

保存動態創建here.So嘗試使用on

$(document).on('click', '#save' ,function() { 
}); 
3

直接委託動態格式事件:

$(document).on('click', '#save' ,function() { 
    //do stuff 
}) 

也許做同樣的:

$(document).on('click', '#click' ,function() { 
    //do stuff 
}) 
+0

感謝您的回答。 – shashank 2013-05-09 13:18:52

0

一旦你添加了元素,你需要重新綁定處理程序或使用jQuery的生活()函數,就像這樣:

$('.span8 .btn').live('click', function() { 
    var input = $("#textarea").val(); 
    alert(input); 
}); 
+0

'live'似乎已被棄用。你必須用'on'來代替。像其他帖子所暗示的那樣。 – 2013-05-09 12:49:44

0

檢查這...

$('BTN「。)點擊(函數(){

var input = $("#textarea").val(); 
    alert(input); 

});