一个函数如何找到最初称为函数的锚的父元素? [英] How can a function find a parent element of the anchor which originally called the function?

查看:110
本文介绍了一个函数如何找到最初称为函数的锚的父元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个正在调用函数的锚标记:

 < a href =#id =addPersononClick =addPerson(); return false;>添加客人< / a> 

仅供参考,这是所调用的函数:

 函数addPerson(){
//当前记录我们有多少行。
current ++;
console.log($(this).parent('form')。attr('id'));
var strToAdd ='< div class =row> \
< div class =column grid_2> \

我希望允许此功能在单个页面上的多个表单上工作。所以我的想法是回到树的父表单元素,获取它的id并使用它(以某种方式)来允许该函数在页面中的多个表单上工作。



你可以看到我试着用一个快速的console.log来测试我的想法,但它一直回来未定义。我也尝试在anchor标记本身中运行console.log,但它也是Undefined。



我测试过.parents(),它在锚点标记,但不在函数iteslf中。



任何建议?

解决方案

添加到父母身上,然后您就可以在自己的功能中使用适当的范围。因此:

pre $ < a href =#id =addPersononClick =addPerson($(this));返回false;>添加客人< / a>

然后在函数中使用:

 函数addPerson(anchorElement){
var form = anchorElement.parents(form);
//等。
}


Ok, the question alone is making my head spin.

I have an anchor tag that is calling a function:

<a href="#" id="addPerson" onClick="addPerson(); return false;">Add a Guest</a>

Just for reference, this is the function that's being called:

function addPerson() {
//current keeps track of how many rows we have.
current++;
console.log($(this).parent('form').attr('id'));
var strToAdd = '<div class="row">\
          <div class="column grid_2">\
            <label for="two-guests-name'+current+'">Guest '+current+':</label>\
          </div>\
          <div class="column grid_5">\
            <input name="two-guests-name'+current+'" type="text" id="two-guests-name'+current+'" value="Name" onfocus="RemoveFormatString(this, \'Name\')" /> \
            <input name="two-guests-age'+current+'" type="text" class="guestage digits" id="two-guests-age'+current+'" value="Age" size="4" maxlength="3" onfocus="RemoveFormatString(this, \'Age\')" />\
          </div>\
        </div>'

$('#numberguests').append(strToAdd)
};

I'd like to allow this function to work on multiple forms on a single page. So my thinking was to travel back in the tree to the parent form element, get its id and use that (somehow) to allow the function to work on multiple forms in the page.

You can see I tried using a quick console.log to test my idea, but it kept coming back "Undefined". I also tried running the console.log in the anchor tag itself, but it also was "Undefined".

I tested .parents() and it works perfectly in the anchor tag, but not in the function iteslf.

Any suggestions?

解决方案

You should pass $(this) into add parents and then you'll have the proper scope to work with in your function. So:

<a href="#" id="addPerson" onClick="addPerson($(this)); return false;">Add a Guest</a>

and then in the function use:

function addPerson(anchorElement) {
    var form = anchorElement.parents("form");
    //etc.
}  

这篇关于一个函数如何找到最初称为函数的锚的父元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆