请帮我创建一个包含多个变量的函数 - 至少两个......
我有一个用PHP和MySQL创建的表...所有ID都是dinamically创建的,为什么我需要以其他方式捕获它们而不是指定它们。
一小段CODE,用于更好地理解表的结构 - 我已经包含在jsFIDDLE
中function delete_id(id) {
alert (id);
var test = $(this).closest('tr').attr('id');
alert(test);
};
答案 0 :(得分:2)
试试这个:
var test = $('#'+id).closest('tr').attr('id');
你职能中的 $(this)
并不代表你的想法。您需要使用传递到id
的{{1}}并使用function
获取该元素
演示here
答案 1 :(得分:1)
我认为在on方法中使用委托是很好用的。好像我们使用它,它不会将事件冒泡到文档中,也不会为DOM中的那些动态tr下的所有tr或标签创建尽可能多的单击处理程序,这总体上有利于提高性能。
$(document).ready(function(){
$('.ultomonitor').on('click','a', function(){
alert("id of div under a " + $(this).children().attr('id'));
alert("id of tr above a " + $(this).closest('tr').attr('id'));
});
});
答案 2 :(得分:1)
更好的方法
<强> HTML 强>
<a href="#"><div id="8928392" onclick="delete_id(this)"
<强> JS 强>
function delete_id(el) {
var test = $(el).closest('tr').attr('id');
alert(test);
};
或
纯JavaScript方法
function delete_id(el) {
var test = getNearestTableRowAncestor(el).id;
alert(test);
};
function getNearestTableRowAncestor(htmlElementNode) {
while (htmlElementNode) {
htmlElementNode = htmlElementNode.parentNode;
if (htmlElementNode.tagName.toLowerCase() === 'tr') {
return htmlElementNode;
}
}
return undefined;
}