2015-02-08 70 views
0

我想在jsfiddle中做一些表面上很簡單的事情,但它不起作用。基本上,我有一個類「我」的h1 html標籤和一個類「poo」的按鈕。第一次點擊的作品和我的CSS顏色改變,但第二次點擊不起作用?第二個jQuery按鈕點擊不發射

$(".poo").click(function(e){ 
    e.preventDefault(); 
    $(".me").css("color","green"); 
    var haha = $("<button>Click Me!!!</button>"); 
    $(this).after(haha); 
    $(haha).addClass("changer"); 
    $(this).hide(); 

}); 
$(".changer").click(function(e){ 
    e.preventDefault(); 
    $(".me").css("color","black"); 
    $(this).hide(); 
}); 
+0

鏈接到小提琴? – 2015-02-08 05:23:27

+0

我正在創建的新按鈕。 http://jsfiddle.net/edwinkohlbrenner/0yodg7gb/ – Kohl 2015-02-08 05:25:20

回答

2

綁定第二次點擊父元素:

$(document).on('click', '.changer', function() { 
//function here 
}); 
+0

我只是在我的HTML有一個h1和按鈕父母會是什麼? – Kohl 2015-02-08 05:37:03

+0

嘗試'$(document)'。 [FIDDLE](http://jsfiddle.net/0yodg7gb/1/) – sideroxylon 2015-02-08 05:38:41

+0

那爲什麼工作?當點擊處理程序已經綁定時,這意味着什麼? – Kohl 2015-02-08 05:41:13

2

changer點擊處理程序在元素存在之前被綁定。請嘗試使用$.on方法。

http://api.jquery.com/on/

$('body').on('click', '.changer', function() {...}) 

這工作,因爲事件處理程序綁定到文件body,已經存在在頁面上。當在主體的任何位置點擊時,jQuery將檢查點擊的元素是否與選擇器.changer相匹配,如果是,則執行回調。

或者,您可以在第一個回調中綁定$('.changer').click事件。

+0

是這樣的? $( 「轉換 」)上(「 點擊」,功能(E){等等...})。 – Kohl 2015-02-08 05:28:37

+0

我沒有body標籤 – Kohl 2015-02-08 05:36:40

+0

我試過把$('。changer')放到$(this).hide()後面的第一個點擊回調中。並沒有工作 – Kohl 2015-02-08 05:43:34

1

更新小提琴:http://jsfiddle.net/0yodg7gb/7/

$(".poo").click(function(e){ 
     e.preventDefault(); 
     $(".me").css("color","green"); 
     var haha = $("<button>Click Me!!!</button>").addClass('changer'); 
     $(this).after(haha); 
     $(haha).addClass("changer"); 
     $(this).hide(); 
     bindClick(); 
    }); 

function bindClick(){ 
$(".changer").bind('click',function(e){ 
     e.preventDefault(); 
     $(".me").css("color","black"); 
     $(this).hide(); 
}); 
} 
+0

這很酷。因此,你的綁定點擊事件和「重新建立」它?下一級別的東西 – Kohl 2015-02-08 05:52:55

+0

刪除解除綁定。在某些情況下,你需要它。但不是在你的情況。 – 2015-02-08 06:20:16

+0

是否已綁定並取消綁定? – Kohl 2015-02-08 16:43:53

相關問題