在 jQuery 中获取最接近元素的表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19168919/
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-08-26 23:21:05  来源:igfitidea点击:

Get Closest Form to an Element in jQuery

javascriptjqueryhtmlcheckbox

提问by jcobhams

I have this js/jquery script i wrote to check all checboxes with in a form. It works well but this checks all checkboxes that are on page irrespective of the form wrapper they are.

我有我写的这个 js/jquery 脚本来检查表单中的所有复选框。它运行良好,但这会检查页面上的所有复选框,而不管它们是什么表单包装器。

here is the function

这是功能

function toggleCheck(state)
{   var checkboxes = jQuery("form input:checkbox");
if(state==true){checkboxes.prop('checked',true); }
if(state==false){ checkboxes.prop('checked',false); }
}

usage

用法

<a id="check" href="#" onclick="javascript:toggleCheck(true);" class="btn">Select All</a>
<a id="uncheck" href="#" onclick="javascript:toggleCheck(false);" class="btn">Deselect All</a>

Note this works well but my problem is if i have

请注意这很好用,但我的问题是如果我有

 <form action="myaction-page">//some form elements and checkboxes </form>

and

<form action="myaction-page-2">//some form elements and checkboxes </form>

and i click the check all link in form1, all checkboxes gets check including those in form2.

然后我单击 form1 中的 check all 链接,所有复选框都得到检查,包括 form2 中的复选框。

Is there a way to separate them without introducing form ids or names?..this is because i have used it extensively in production code and to rewrite all will be trouble.

有没有办法在不引入表单 ID 或名称的情况下将它们分开?..这是因为我在生产代码中广泛使用了它,重写所有内容都会很麻烦。

Any Help will be greatly appreciated.

任何帮助将不胜感激。

P.S it is worth noting that the select all and deselect all are within both forms and both forms are on the same page.

PS值得注意的是,全选和取消全选都在两个表单中,并且两个表单都在同一页面上。

回答by j08691

Assuming your select/deselect links are inside the form, do:

假设您的选择/取消选择链接在表单内,请执行以下操作:

function toggleCheck(state,elem) {
    jQuery(elem).closest("form").find("input:checkbox").prop('checked', state);
}

And change your link JS to (passing the appropriate true/false parameter):

并将您的链接 JS 更改为(传递适当的 true/false 参数):

onclick="javascript:toggleCheck(false,this);"

jsFiddle example

jsFiddle 示例

回答by Kevin B

the .closest method will do what you want.

.closest 方法会做你想做的。

onclick:

点击:

onclick="toggleCheck.call(this,true);"

js:

js:

function toggleCheck(state) {   
    var checkboxes = jQuery(this).closest("form").find("input:checkbox");
    checkboxes.prop('checked',state || false);
}

回答by nietonfir

The answer is: it depends on your DOM. If your <a>elements are inside the form, you could use $.closest():

答案是:这取决于你的 DOM。如果您的<a>元素在表单内,您可以使用$.closest()

function toggleCheck(state) {
    $(this)
        .closest("form")
        .find("input[type=checkbox]")
        .prop('checked', state);
}

I slightly altered your code to increase readability, performance (see the additional notes regarding the :checkbox selector) and be more "jQuery"-like.

我稍微修改了您的代码以提高可读性、性能(请参阅有关:checkbox 选择器的附加说明)并且更像“jQuery”。

[edit] After reading the comments I rewrote the function, still on the assumption that the <a>elements are inside the <form>, this time also with a working jsFiddle:

[编辑] 阅读评论后,我重新编写了函数,仍然假设<a>元素在 内部<form>,这次也使用了jsFiddle

function toggleCheck(state) {
    $(document).find(event.target)
        .closest("form")
        .find("input[type=checkbox]")
        .prop('checked', state);
}

[edit2] And for the sake of completness regarding my comment about the order of the elements (jsFiddle):

[edit2] 为了完整起见,我对元素顺序的评论(jsFiddle):

function toggleCheck(state) {
    var pos = $(document).find(event.target.localName + "." + event.target.className).index(event.target);
    var $form = $($(document).find("form").get(Math.floor(pos/2)));
    $form
        .find("input[type=checkbox]")
        .prop('checked', state)
}

[edit3] The last edit, I promise. This time I ignore the default callback and do my own thing:

[edit3] 最后一次编辑,我保证。这次我忽略默认回调并做我自己的事情

function toggleCheck(state) {
    // either write the s tate now in a variable for
    // the next callback
}

$(document).on("click", "a.btn", function(e) {
    var $ele = $(this);
    // or do some string exploration
    var toggle = $ele.attr("onclick").indexOf("true") > -1;

    var pos = $(document).find("a.btn").index($ele);
    var $form = $($(document).find("form").get(Math.floor(pos/2)));
    $form
        .find("input[type=checkbox]")
        .prop('checked', toggle);
});

Works without having to touch anything. But I wouldn't want to use this. ;-)

无需接触任何东西即可工作。但我不想使用这个。;-)

回答by Speedy

You can also just apply a data-target to your anchors and eval based on the action of your form elements:

您还可以根据表单元素的操作将数据目标应用于锚点和评估:

... data-target='myaction-page' ...

... checkboxes[i].form.getAttribute( 'action' ) ...

Shown in detail on this JSFiddle

在此JSFiddle上详细显示