javascript 在javascript中查找表单ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4274704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:51:09  来源:igfitidea点击:

Finding the form Id in javascript

javascript

提问by Novice

I have a main page (Home.aspx) and on selecting a link from the menu i send an asynchronous request to the server and load the response (another aspx page) inside jquery tabs.

我有一个主页 (Home.aspx),在从菜单中选择一个链接时,我向服务器发送一个异步请求并在 jquery 选项卡中加载响应(另一个 aspx 页面)。

Now i have different hyperlinks inside the pages and on click i call a method in an external js file. How do i get the form id of the clicked hyperlink.

现在我在页面中有不同的超链接,单击时我会调用外部 js 文件中的方法。如何获取单击的超链接的表单 ID。

To be simple on click of a hyperlink calls a method, will i get the id of the form to which the hyperlink belongs.

为了简单点击超链接调用一个方法,我会得到超链接所属表单的ID。

回答by BGerrissen

If you don't use a javascript toolkit/framework and don't care to learn good practises and simply want to get the job done.

如果您不使用 javascript 工具包/框架并且不关心学习好的实践并且只想完成工作。

<!-- inside a form somewhere -->
<a href="url" onclick="javascript:doStuff(this);">link text</a>

<!-- somewhere else in your page, where you put javascript -->
<script>
    function doStuff(node) {
        var ancestor = node.parentNode;
        var formID;
        while( ancestor && ancestor !== document ) {
            if ( /^form$/i.test( ancestor.nodeName ) ) {
                formID = ancestor.id;
                break;
            }
            ancestor = node.parentNode;
        }
        if ( formID ) {
            // do stuff with formID
        }
    }
</script>

If you use jQuery:

如果您使用 jQuery:

$("form a").click(function(e){
    var formID = $(this).closest("form").attr("id");
    if( formID ) {
        // do stuff with formID
    }
});

回答by Gabi Purcaru

I have no idea how your code looks like, but what you are asking would be something like

我不知道你的代码是什么样子,但你要问的是

$("#container a").click(function () {
    if($(this).parent().attr('id') == "the_form_you_need") {
        do_stuff_with_it();
    }
});

回答by Caleb

I think you're going to have to walk the DOM tree starting at the link node and going up by parent until you find a form node. Conceptually the code would look something like this:

我认为您将不得不从链接节点开始遍历 DOM 树,然后由父节点向上遍历,直到找到表单节点。从概念上讲,代码看起来像这样:

node = link;
while (node.type != form) {
    node = node.parent;
}
form.id = node.id;