简体   繁体   English

如何使用JQuery获取正文中第一个元素(窗体)的ID?

[英]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 . 使用之间的空间bodyform ,并删除. . 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"));

Demo 演示

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");

Demo 演示

您可以尝试以下方法:

$('form').attr('id')

How to get id of first element (form) in body using JQuery? 如何使用JQuery获取正文中第一个元素(窗体)的ID?

This will get you the first form element's id in the body 这将使您获得体内的第一个表单元素的ID

$('body').find('form').eq(0).attr('id');

Demo 演示

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

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