我正在使用 jQuery 创建一个包含图像的表格。我的 js 代码如下所示:
$(document).ready(function() {
var korpusArray = new Array();
$.getJSON("file.js", function(data) {
var korpusId;
var korpusChooseTable = "<table id='TableKorpusGaleria'><tbody><tr>";
$.each(data, function(i, value) {
korpusArray.push(value.text);
strRemove = value.filename.replace("korpus/", "");
korpusChooseTable += '<td><p>'+value.title+'</p><p style="display:none;">'+value.id+'</p></br><img src="/korpus/thumbs/phoca_thumb_s_'+strRemove+'"></td>';
});
korpusChooseTable += '</tr></tbody></table>';
$("#korpusChoose").html(korpusChooseTable);
console.log(korpusArray.length);
console.log(data.length);
});
// after this I wanna click on table cell and do some function but
// it doesnt work. Can somebody tell me what I'm doing wrong?
$("#korpusChoose #TableKorpusGaleria tbody td").click(function() {
alert();
});
});
最佳答案
对动态创建的项目使用委托(delegate) - 如果该元素在绑定(bind)时不存在...通常处于 dom 就绪状态 - 则不会附加任何事件处理程序
jQuery 1.7 及更高版本 http://api.jquery.com/on/
$("#korpusChoose ").on('click','#TableKorpusGaleria tbody td',function(){
alert();
});
或 jQuery 1.6 降至 jQuery 1.4.3 http://api.jquery.com/delegate/
$("#korpusChoose ").delegate('#TableKorpusGaleria tbody td','click',function(){
alert();
});
block 引用>Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
另一种方法是在将其添加到 dom 后立即添加
$("#korpusChoose").html(korpusChooseTable);
然后就在
$("#korpusChoose #TableKorpusGaleria tbody td").click(function(){ alert(); });
尽管后者效率较低,因为您将事件处理程序绑定(bind)到表中的每个 td 元素 - 使用委托(delegate),您只需将其绑定(bind)到 dom 中存在的父元素,并在事件冒泡时处理该事件
关于jquery - 无法点击用jquery创建的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496022/