简体   繁体   English

使用jQuery在表单中选择父项然后子项

[英]Selecting a parent and then children in a form using jQuery

I have a loop in my server side script that puts out many forms in this variety: 我的服务器端脚本中存在一个循环,其中列出了各种形式的多种形式:

<form class="myForm">
    <input type="checkbox" class="myCheckbox" />
    <div>
         <span class="myButton active">Button 1</span>
         <span class="myButton">Button 2</span>
         <div clas="myDiv">
             <select class="mySelect">
                 <option></option>
                 ...
                 <option></option>
             </select>
         </div>
    </div>
</form>

From .myCheckbox I need to be able to access/select only the nested 2 .myButton's in this form and access to the nested .mySelect. 从.myCheckbox,我需要能够以这种形式访问/选择仅嵌套的2 .myButton,并访问嵌套的.mySelect。 What's the proper selectors? 什么是合适的选择器?

Remember I have lots of these forms on the page and only want the one I'm on. 记住,我在页面上有很多这样的表格,只想要我正在使用的表格。

I have started: 我已经开始了:

$('body').on('change', '.myCheckbox', function () {
  if ($(this).is(':checked')) 
    ...

Thanks. 谢谢。

Shouldn't something like this work: 不应该像这样的工作:

var $form     = $(this.form);
var $elements = $form.find('.myButton,.mySelect');

Of course, you could accomplish this in other ways by looking at siblings, or traversing the dom. 当然,您可以通过查看兄弟姐妹或遍历dom来以其他方式完成此操作。 But more than likely your form will have elements added to it, or removed from it. 但是,您的表单很有可能会添加或删除元素。 Finding the common ancestor (eg, the form element) would help make your application scalable and more robust for future changes. 查找共同祖先(例如,表单元素)将有助于使您的应用程序具有可伸缩性,并且对于将来的更改更加健壮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM