我一直没能找到这个答案。我不知道我是否搜索错误或我的词典不正确,但我试图获取一组 jquery 单选按钮的选定元素。这是我的 JS 代码:
var hideFieldsBasedOnRadioButtonValue = function () {
var $employmentStatusRadioButtons = $(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']");
var displayOrHideRequiredFields = function ($radioButton) {
if ($radioButton.val() === "Full Time" || $radioButton.val() === "Part Time") {
$radioButton.closest("div.form-row").next(".required-input-when-yes").removeClass("d-none");
} else {
$radioButton.closest("div.form-row").next(".required-input-when-yes").addClass("d-none");
}
}
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
$employmentStatusRadioButtons.on("change", function () {
displayOrHideRequiredFields($(this));
});
}
这是该函数的精简版本。我还有几个单选按钮,需要根据单选按钮的值隐藏或显示其他字段。我遇到的具体问题是我想 trim 这一行:
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
$employmentStatusRadioButtons 是 jquery 对象的集合,我无法弄清楚如何获取选定的对象。任何帮助都会很棒。
我不想在这一行和代码的第 2 行上使用相同的“.edit-profile-employment-information input[name='user[profile_attributes][employment_status]']”选择器,而是执行类似
displayOrHideRequiredFields($employmentStatusRadioButtons:checked);
现在这行不通了。我最接近的方法是执行以下操作;
displayOrHideRequiredFields($employmentStatusRadioButtons.selector + ":checked")
但我不太喜欢它的样子。我们没有使用 ES6,否则那就太棒了。
在这方面我找不到任何可以帮助我的东西。有谁知道我可以做这样的事情的具体方法吗?
最佳答案
您可以使用jquery filter()
使用 jQuery 对象过滤变量的函数。
var $radios = $('[name=test],[name=test2]');
var $radiosFiltered = $radios.filter(':checked');
$radiosFiltered.each(function(){
console.log($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" value="1" checked>
<input type="radio" name="test" value="2">
<input type="radio" name="test" value="3">
<input type="radio" name="test2" value="4">
<input type="radio" name="test2" value="5" checked>
<input type="radio" name="test2" value="6">
关于javascript - Jquery 从被检查的 jquery 对象集合中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561440/