在另一个元素中选择一个元素,这种方法有效吗?如果没有,我该怎么办?
<table class="tableData" id="addUserTable" >
<tr>
<th class = "" name="errorMsgUser" id="errorMsg" value="" colspan="2"> </th>
</tr>
<tr>
<th class= "" > Desired Username <span class="required">*</span></th>
<td><input name="desUname" type="text" id="desUname" size="30" value="" /></td>
</tr>
<tr>
<th class= "" > Password <span class="required">*</span></th>
<td><input type="password" name="password" id="password" value="" size="30" /></td>
</tr>
<tr>
<th></th>
<td>
<input name="submitAddUser" type="submit" id="submitAddUser" value="Add User" />
<input type="button" value="Clear All" id="clearUpdateForm"></input>
</td>
</tr>
</table>
单击“clearUpdateForm”按钮后,我已成功清除所有表单条目。然后如何聚焦第一个输入文本框?我想要一个通用的解决方案。到目前为止,这是我的 jquery 脚本:
$(function(){$("#clearUpdateForm").click(function(){
$(this).parents('form').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}});
$('input#desUname').focus();
});});
我可以用这两行替换最后一行代码吗:
var parentId = "#" + $(this).parents('form').attr("id") ;
$("parentId input[type=text]:first").focus();
<table class="tableData" id="addUserTable" >
<tr>
<th class = "" name="errorMsgUser" id="errorMsg" value="" colspan="2"> </th>
</tr>
<tr>
<th class= "" > Desired Username <span class="required">*</span></th>
<td><input name="desUname" type="text" id="desUname" size="30" value="" /></td>
</tr>
<tr>
<th class= "" > Password <span class="required">*</span></th>
<td><input type="password" name="password" id="password" value="" size="30" /></td>
</tr>
<tr>
<th></th>
<td>
<input name="submitAddUser" type="submit" id="submitAddUser" value="Add User" />
<input type="button" value="Clear All" id="clearUpdateForm"></input>
</td>
</tr>
</table>
When the button "clearUpdateForm" is click, I've managed to clear all the form entries.How do I then focus the first input text-box ? I want a generic solution. This is my jquery script so far :
$(function(){$("#clearUpdateForm").click(function(){
$(this).parents('form').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}});
$('input#desUname').focus();
});});
Can i replace the last lin of code by these two lines:
var parentId = "#" + $(this).parents('form').attr("id") ;
$("parentId input[type=text]:first").focus();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最后一行可以替换为
last line can be replaced by
如果您将第二行更改为:
或者您可以简单地使用:
这样即使表单没有任何 ID,它也会起作用。
This will work if you change the second line to:
Or you can simply use:
This way it will work even if the form does not have any ID.