简体   繁体   English

如何获取一个对象的“值”属性<input> html中的元素?

[英]How to acquire the "value" attribute of an <input> element in html?

Suppose there is an <input> element.假设有一个<input>元素。 When I use jQuery to acquire the attributes of this element, following is my code:当我使用jQuery获取该元素的属性时,以下是我的代码:

 console.log($("#radio").attr("type")); console.log($("#radio").attr("value"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="radio" type="radio" value="a" />

and the result is: radio undefined结果是:无线电未定义

why can't I acquire the "value" attribute?为什么我不能获得“价值”属性?

Converting my comments to answer for the sake of posting examples为了发布示例而将我的评论转换为答案

$("#radio").val() is the normal way. $("#radio").val()是正常方式。

Do NOT have TWO radios with the same ID.不要有两个具有相同 ID 的收音机。 IDs must be unique ID 必须是唯一的

Radios must have the same NAME so a click on one will remove the checked from the other.收音机必须具有相同的名称,因此单击一个将从另一个中删除选中的。

You can get the value of the checked named radio as $("[name=radio]:checked").val()您可以通过$("[name=radio]:checked").val()获取选中的命名收音机的值

Here I on purpose leave the duplicate IDs and you will see it gets the value of the first only when accessed via ID在这里,我故意留下重复的 ID,你会看到它只有在通过 ID 访问时才获得第一个的值

It is not possible to get undefined in this setup unless you call the script before the radios exist除非您在收音机存在之前调用脚本,否则在此设置中不可能未定义

You might want to wrap in a load event handler in case the radios are not available in the DOM when your script runs如果脚本运行时 DOM 中的收音机不可用,您可能希望包装在加载事件处理程序中

 $(function() { // when page loads console.log($("#radio").val()) console.log($("#radio").attr("value")); console.log($("[name=radio]:checked").val()) $("[name=radio]").on("click", function() { console.log(this.value, $(this).val()); // either will work }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="radio" name="radio" type="radio" value="b" /> <input id="radio" name="radio" type="radio" value="a" checked/>

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

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