2013-10-14 48 views
0

我有一個按鈕監聽器如下:獲取參數與jQuery附加按鈕

$('body').on('click', '.showrecent', function() { 
    $('#display').toggle(); 
}); 

我有一個JSON搜索(我在哪裏追加一個按鈕):

var search = 0; 
$.getJSON('data.json', function(data) { 
    if ((this.Name.toLowerCase()).indexOf(sr) > -1) { 
     id++; 

    //blah blah blah 

    var recent = "<button class = 'showrecent' onclick = 'showrecent(id)'>Recent Transaction</button>"; 

    $('#founded').append(recent); 

    }); 
}); 

基本上,我想通過id與showrecent功能! 任何幫助,高度讚賞!

回答

2

如果您希望每個人在函數調用中都有自己的id,則需要連接。

var recent = "<button class = 'showrecent' onclick = 'showrecent(" + id + ")'>Recent Transaction</button>"; 

另一種方法是使用jQuery來綁定處理程序。

id++; 

var thisid = id; 
$("<button>", {className:'showrecent', 
       text:" Recent Transaction", 
       click: function() { 
        showrecent(thisid); 
       } 
}).appendTo('#founded'); 
+1

現在我覺得很蠢。我在那裏想如何傳遞一個字符串中的變量。謝謝! – WhatisSober

1
var recent = "<button class='showrecent' onclick='showrecent(" + id + ")'>Recent Transaction</button>"; 
1

如果不使用內聯事件處理程序,則會更好。

var recent = $("<button class ='showrecent'>Recent Transaction</button>"); 
recent.data("id",id); 
recent.on("click",showrecent); 
$('#founded').append(recent); 

和功能

function showrecent() { 
    var btn = $(this); 
    var id = btn.data("id"); 
    console.log(id); 
} 

如果你想這樣做你正在做的方式,建立了繩子。

var recent = "<button class = 'showrecent' onclick = 'showrecent(" + id + ")'>Recent Transaction</button>"; 
+0

謝謝,但由於某種原因,按鈕doesnot調用showrecent()...任何線索?也許是因爲該按鈕是在DOM之後添加的? – WhatisSober