1. 程式人生 > >js動態生成按鈕的響應

js動態生成按鈕的響應

動態新增按鈕:

function_name: function (data) {    
        var self = this;
		var info = null;
        $(".step").hide();
        $("#stepAddvisitor").show();
	
        if (data != null && data != '') {
            info = eval('(' + data + ')');
            $("#visitorinfo").append("<tr><td>"+info.name+"</td><td><button type=\"button\" class=\"btn delete\">刪 除</button></td></tr>");
        } 
		
        self.startCountDown(60);
    }

刪除響應:

//刪除  
$(".delete").click(function(){
    $(this).parents("tr").remove(); 
    //其他
});

這時候響應沒有寫在function裡,會發現動態生成的按鈕是無法響應的。

方法一:

只要把響應寫在函式裡就可以解決這個問題。

function_name: function (data) {    
        var self = this;
		var info = null;
        $(".step").hide();
        $("#stepAddvisitor").show();
	
        if (data != null && data != '') {
            info = eval('(' + data + ')');
            $("#visitorinfo").append("<tr><td>"+info.name+"</td><td><button type=\"button\" class=\"btn delete\">刪 除</button></td></tr>");
        } 
		
		//刪除  
		$(".delete").click(function(){
			$(this).parents("tr").remove(); 
		});
		
        self.startCountDown(60);
    }

方法二:

js動態生成元素的時候給他加上 onclick之類的方法來響應

$("#visitorinfo").append("<tr><td>"+lastrow+"</td><td><button type=\"button\" class=\"btn delete\" onclick=\"myfunction()\">刪 除</button></td></tr>");

原因是 

在頁面給元素註冊點選事件的時候    $(".delete").click(function(){   XXXX   });     JS動態生成的元素還尚未生成,所以click事件就沒有生效。