2012-05-20 40 views
0

基本上我創建了一個覆蓋這裝入appendTo爲「加載屏幕」。添加可用按鈕.AppendTo - Jquery的

最近,我需要添加一個停止按鈕到覆蓋這不是一個問題,但是jQuery的.click函數沒有拿起按鈕點擊,我試着保留現有的按鈕,因此它會也許註冊,但可悲的是沒有。

(我也使用的ID爲按鈕也試過

下面是一些測試代碼來演示該問題

$(document).ready(function(){ 
    $("#addButton").click(function() { 
     $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
     $overlay.appendTo(document.body); 
     $("#stop").click(function() { 
      alert("working"); 
     }); 
    }); 

編輯:。

只是爲了澄清,這就是我本來想的,但是由於「過度變化」上面的例子將在我的情況下工作,這是最初的問題只是爲了清楚起見。

$(document).ready(function(){ 
     $("#addButton").click(function() { 
      $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
      $overlay.appendTo(document.body); 

     }); 

$("#stop").click(function() { 
       alert("working"); 
      }); 

}); 
+0

可能重複的[觸發新添加的jQuery HTML代碼(http://stackoverflow.com/questions/10677194/jquery-triggered-newly-added-html-code) – samjudson

+1

WORKSFORME:HTTP://的jsfiddle。 net/3HMcT/ – Bergi

+0

@samjudson:不,這是不同的。 '#stop'將在'$('#stop')之前的DOM中。click(...)'被調用以將處理程序綁定到它。 –

回答

1

是的,你也可以這樣做。請參閱docs for the on() method

$(document).ready(function(){ 
    $("#addButton").click(function() { 
     $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
     $overlay.appendTo(document.body); 
    }); 

    $(document).on("click", "#stop", function() { 
     alert("working"); 
    }); 
}); 

這僅增加了一個點擊監聽器文件,其中每觸發一個click事件從#stop元素泡時間。但是,這通常只需要很多元素,所以當有多個這樣的按鈕時,最好使用「stop」類。

不過,我想你會需要你在執行權的onclick-行動的第一個例子不得不關閉。

1
$(document).ready(function(){ 
    $("#addButton").on('click', function() { 
     $overlay = $("<div id='overlay'><div id='contain'><h3 style='color:#FFF'>Processing, just a moment</h3> <div id='stop'><button type='button' class='btn btn-primary' id='stop1' >Stop</button></div><div class='bar' style='width: 80%; padding-top:50%'></div></div></div"); 
     $overlay.appendTo(document.body); 
    }); 

    $(document).on('click', '#stop', function() { 
     alert("working"); 
    }); 
}); 
+0

ü不要複製我的代碼!我8秒更快:-) – Bergi

+0

@Bergi是的,我注意到了!不,我沒有複製你的代碼,只是寫了幾乎相同的東西? – adeneo

+0

我知道你不可能複製它,但我真的認爲這將是完全一樣的:-)剛開始認識的差異不大... +1的雙重用途。對()的 – Bergi