gpt4 book ai didi

jquery - 我如何使用 jQuery 获取所有表单元素(输入、文本区域和选择)?

转载 作者:IT王子 更新时间:2023-10-29 03:25:18 25 4
gpt4 key购买 nike

在 jquery 中是否有一种简单的方法(无需单独列出它们)来选择所有表单元素并仅选择表单元素。

我不能使用 children() 等,因为表单包含其他 HTML。

例如:

$("form").each(function(){
let $inputs = $("input, textarea, select", this);
});

最佳答案

编辑:正如评论(Mario AwadBrock Hensley)中所指出的,使用.find 来获取 child

$("form").each(function(){
$(this).find(':input') //<-- Should return all input elements in that specific form.
});

表单也有一个元素集合,有时这与子元素不同,例如当表单标签位于表格中且未关闭时。

var summary = [];
$('form').each(function () {
summary.push('Form ' + this.id + ' has ' + $(this).find(':input').length + ' child(ren).');
summary.push('Form ' + this.id + ' has ' + this.elements.length + ' form element(s).');
});

$('#results').html(summary.join('<br />'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="A" style="display: none;">
<input type="text" />
<button>Submit</button>
</form>
<form id="B" style="display: none;">
<select><option>A</option></select>
<button>Submit</button>
</form>

<table bgcolor="white" cellpadding="12" border="1" style="display: none;">
<tr><td colspan="2"><center><h1><i><b>Login
Area</b></i></h1></center></td></tr>
<tr><td><h1><i><b>UserID:</b></i></h1></td><td><form id="login" name="login" method="post"><input
name="id" type="text"></td></tr>
<tr><td><h1><i><b>Password:</b></i></h1></td><td><input name="pass"
type="password"></td></tr>
<tr><td><center><input type="button" value="Login"
onClick="pasuser(this.form)"></center></td><td><center><br /><input
type="Reset"></form></td></tr></table></center>
<div id="results"></div>


可能是:input选择器就是你想要的

$("表单").each(函数(){ $(':input', this)//<-- 应该以该特定形式返回所有输入元素。});

正如文档中指出的

To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

你可以像下面这样使用,

$("form").each(function(){
$(this).filter(':input') //<-- Should return all input elements in that specific form.
});

关于jquery - 我如何使用 jQuery 获取所有表单元素(输入、文本区域和选择)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12862601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com