[英]How to get id of first element (form) in body using JQuery?
Not much familiar with JQuery; 对JQuery不太熟悉; I want to get id of form element in jquery which is located in following location
我想在以下位置的jquery中获取表单元素的ID
<body>
<div id="boxDialog"> </div>
<div class="container">
<div class="header">
Many Tables and divs
</div>
</div>
<form id="approval"></form>
Jquery: : :
alert($("body.form").attr("id"));
Fiddle: https://jsfiddle.net/j32f9128/ 小提琴: https : //jsfiddle.net/j32f9128/
Problem: 问题:
body.form
will select the body
element having class of form
, which doesn't exists so returns undefined
. body.form
将选择具有form
类的body
元素,该类不存在,因此返回undefined
。
Solution: 解:
Use space between the body
and form
and remove .
使用之间的空间
body
和form
,并删除.
. 。 Using space, the
form
element will be searched in body
. 使用空间,将在
body
搜索form
元素。
alert($("body form").attr("id"));
You can also ommit body
here as all the forms
are nested inside body
. 您还可以在此处省略
body
,因为所有forms
都嵌套在body
内部。
alert($("form").attr("id"));
If you want to get the id
of first form element, you can use first()
. 如果要获取第一个表单元素的
id
,则可以使用first()
。
alert($("form").first().attr("id"));
Or you can also 或者你也可以
alert($("form:first").attr("id"));
You have used form
as classname. 您已将
form
用作类名。 your selector tries to find element body that has class form
您的选择器尝试查找具有类
form
元素主体
You should rather use space that indicate matching against descendants or find selector along with tagname selectors for both body and form: 您应该使用用于指示与后代匹配的空间,或者为主体和形式使用查找选择器以及标记名选择器:
$("body form").attr("id");
which is equivalent to 相当于
$("body").find("form").attr("id");
您可以尝试以下方法:
$('form').attr('id')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.