获取与jQuery中的元素最接近的形式 [英] Get Closest Form to an Element in jQuery

查看:47
本文介绍了获取与jQuery中的元素最接近的形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个js/jquery脚本来检查所有Checboxes的形式.效果很好,但这可以检查页面上的所有复选框,而不管它们是表单包装器是什么.

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.

这是功能

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

用法

<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>

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

然后单击"form1"中的"check all"链接,所有复选框(包括form2中的复选框)都会被选中.

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

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

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.

任何帮助将不胜感激.

P.S值得注意的是,全选和取消全选都在两种形式内,并且两种形式都在同一页面上.

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.

推荐答案

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

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

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

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

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

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

jsFiddle示例

jsFiddle example

这篇关于获取与jQuery中的元素最接近的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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