函数如何找到最初调用函数的锚的父元素?
好吧,仅凭这个问题让我头晕目眩。
我有一个调用函数的锚标记:
Add a Guest
仅供参考,这是被调用的函数:
function addPerson() { //current keeps track of how many rows we have. current++; console.log($(this).parent('form').attr('id')); var strToAdd = '\ \ \ \ \ \ \ \ ' $('#numberguests').append(strToAdd) };
我想允许此function在单个页面上处理多个表单。 所以我的想法是在树中返回到父表单元素,获取它的id并使用它(以某种方式)允许该函数在页面中的多个表单上工作。
你可以看到我尝试使用一个快速的console.log来测试我的想法,但它一直回来“未定义”。 我也尝试在锚标记本身中运行console.log,但它也是“Undefined”。
我测试了.parents(),它在锚标签中完美运行,但在函数iteslf中却没有。
有什么建议?
您应该将$(this)传递给添加父项,然后您将在您的函数中使用适当的范围。 所以:
Add a Guest
然后在函数中使用:
function addPerson(anchorElement) { var form = anchorElement.parents("form"); //etc. }
不要使用onclick
属性使用jQuery事件绑定。 由于您没有提供有关标记的任何信息,您需要自己填写选择器
//this binds the same function to all a tags specified by the selector $("form somemoreselectorgotgettheright a").bind("click", function() { console.log($(this).parent("form").attr("id")); .... });
this
背景是不同的。 将onclick更改为:
addPerson.call(this);
这将使函数中的this
与锚标记中的this
匹配。
或者更好的是,根本不要使用onclick属性,而是使用jQuery事件处理程序附件,如下所示:
$(document).ready(function() { $('#addPerson').click(function(ev) { ev.preventDefault(); // Do something with $(this), which is the anchor tag }); });
而你的锚标签上没有任何点击处理程序:
Add a Guest
使用带有选择器的parents()(这将向上搜索所有父项,直到我找到的匹配)。 例如
$(this).parents('form').[...]
传入id作为参数。 例如
Add a Guest then... function addPerson(parent_id) { // do something with parent_id