【发布时间】:2011-12-03 19:26:35
【问题描述】:
以下代码的工作原理如此之多,以至于它创建了表并附加了行。
但是,我已将单击事件附加到位于 <tfoot> 中的动态创建的按钮上,但它不起作用。它似乎没有调用createNewIssue 函数,也不会产生任何Firebug 错误。我将其更改为仅发出一个简单的警报,但这也不起作用。
我对 jquery 还是很陌生,所以如果有更好的方法可以做到这一点,那就太好了,但希望至少有人能够帮助我理解为什么我的 tfoot 按钮不起作用......
首先...
$(document).ready(function() {
//add-section works
$('#add-section').click(function() {
createNewSection();
});
//this does not work
$('input[id^=add-issue-]').click(function() {
alert($(this).attr('id')); //put this in and it fails
//this is what I really want it to do:
var issueid = $(this).attr('id');
createNewIssue(issueid);
});
});
这是createNewSection 函数,它有效:
function createNewSection() {
var sectioncount = $('input.section-title').length;
var issuecount = $('input.issue-title').length;
var newsection = $('input#add-section-textfield').val();
//Add section entry to table
var sinput = document.createElement("input");
sinput.setAttribute("type", "text");
sinput.setAttribute("name", "section["+sectioncount+"][title]");
sinput.setAttribute("id", "section-"+sectioncount+"-title");
sinput.setAttribute("value", newsection);
//Issue title input
//Add section entry to table
var iinput = document.createElement("input");
iinput.setAttribute("type", "text");
iinput.setAttribute("name", "add_issue_"+sectioncount);
iinput.setAttribute("id", "add-issue-"+sectioncount);
iinput.setAttribute("value", "");
//Button to add issue entry to table
var issuebutton = document.createElement("input");
issuebutton.setAttribute("type", "button");
issuebutton.setAttribute("name", "add_issue_"+sectioncount);
issuebutton.setAttribute("id", "add-issue-"+sectioncount);
issuebutton.setAttribute("value", "Add Issue");
var sTable = $('<table>').attr('id', 'section-'+sectioncount).appendTo('#sections');
var sTbody = $('<tbody>').appendTo(sTable);
var sTrow = $('<tr>').appendTo(sTbody);
var sTcell = $('<td>').attr('colspan', 2).html(sinput).appendTo(sTrow);
var sTfoot = $('<tfoot>').appendTo(sTable);
var sTfootRow = $('<tr>').appendTo(sTfoot);
var sTfootCell = $('<td>').html(iinput).appendTo(sTfootRow);
var sTfootCell2 = $('<td>').html(issuebutton).appendTo(sTfootRow);
}
最终,我试图让 createNewIssue 函数向<table id="section-...> 添加一行(包含一个嵌套表),但现在,我只是想让它抛出一个带有 id 的警报父表...
function createNewIssue(issueid) {
var sTable = $(id).parent().parent().attr('id');
alert(sTable);
}
【问题讨论】:
-
永远不需要使用
.attr()来获取元素的ID。始终使用this.id而不是$(this).attr('id')。 stackoverflow.com/questions/4651923/…
标签: jquery dynamic html-table