我正在按钮点击创建表格,效果很好。然后我有一个热键为这些表添加额外的行。我需要获取光标所在的表的父ID,但它一直给我未定义。我可以得到父div id,但是当我把表放入其中时,我的定义是未定义的。任何帮助将不胜感激
$(document).ready(function() {
$("#divNarrative1").keypress(function(e){
alert(e.target.id);
var msgId = $( this ).closest( 'table' ).attr( 'id' );
alert(msgId);
});
});
答案 0 :(得分:2)
我相信table
位于divNarrative1
内。在keypress
this
将指向divNarrative1
并在其上调用closest
将不会为您提供所需的table
。您应该使用e.target
代替this
。
$(document).ready(function() {
$("#divNarrative1").keypress(function(e){
alert(e.target.id);
var msgId = $(e.target).closest('table').attr('id');
alert(msgId);
});
});
更新:按OP
继承创建表格的js
// Insert HTML table
function InsertTable() {
var div = document.getElementById('divNarrative1'); // table reference
div.focus();
document.getElementById("hfProjectBoxNumber").value = Number(document.getElementById("hfProjectBoxNumber").value)+ 1;
document.getElementById("hfBillTextNumber").value = Number(document.getElementById("hfBillTextNumber").value)+ 1;
var projdiv = "Projectbox" + document.getElementById("hfProjectBoxNumber").value
//create table
var tbl = document.createElement('table');
tbl.id = projdiv;
tbl.width = "570px";
tbl.setAttribute("table-layout", "fixed");
tbl.setAttribute("border", "1");
tbl.setAttribute("height", "50px");
tbl.border = 1;
//create header row
var oRow = tbl.insertRow(-1);
var oCell = oRow.insertCell(-1);
oCell.width = "570px";
oCell.setAttribute("colspan", "2");
oCell.setAttribute("align", "center");
oCell.innerHTML = projdiv;
//create coumns
var oRow = tbl.insertRow(-1);
var oCell = oRow.insertCell(-1);
oCell.width = "430px";
oCell.innerHTML = "DESCRIPTION";
oCell.setAttribute("align", "center");
var oCell2 = oRow.insertCell(-1);
oCell2.width = "140px";
oCell2.innerHTML = "AMOUNT";
oCell.setAttribute("align", "center");
div.appendChild(tbl);
return false;
}
继承页面上的html
</div>
<asp:Button ID="btnEditNarr" runat="server" Text="Edit Narrative" />
<input type="button" value="Clear all Content" onclick="clearBilltextbox();"/>
<input type="button" value="Save Content" onclick="getallcontent();"/>
</asp:Panel>