gpt4 book ai didi

javascript - 读取单选按钮的值时,值未定义

转载 作者:行者123 更新时间:2023-11-28 17:06:31 27 4
gpt4 key购买 nike

我正在尝试获取所选单选按钮的值。我尝试了以下方法,但我得到的值为 undefined .

var nameSelected;
$('.m-radio-inline input').on("change", function() {
nameSelected = $('input[name="abc"]:checked').val();
});
alert(nameSelected);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-radio-inline">
<label class="m-radio">
<input type="radio" name="abc" value="Ash" checked>
Ash
<span></span>
</label>
<label class="m-radio">
<input type="radio" name="abc" value="Win">
Win
<span></span>
</label>
</div>

它应该给 Ash/Win

最佳答案

因为它在 nameSelected 具有值之前发出警报 - 将 alert 放入 change 处理程序中:

var nameSelected;
$('.m-radio-inline input').on("change", function() {
nameSelected = $('input[name="abc"]:checked').val();
alert(nameSelected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-radio-inline">
<label class="m-radio">
<input type="radio" name="abc" value="Ash" checked>Ash
<span></span>
</label>
<label class="m-radio">
<input type="radio" name="abc" value="Win">Win
<span></span>
</label>
</div>

关于javascript - 读取单选按钮的值时,值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55723927/

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