向此 JavaScript 添加多个排除项

Add multiple exclusions to this javascript

本文关键字:排除 JavaScript 添加 向此      更新时间:2023-09-26

>最近有人给了我这个代码来解决我的单选按钮问题,它工作得很好,但我如何排除更多的单选按钮组?

我还想排除"lunch_fruitjuice"和"lunch_desserts"

$(function(){
    // cache the selector for all target radio buttons for later use
    var targetRadioButtons = $("input:radio").not("input:radio[name=lunch_desserts]");
    targetRadioButtons.change(function(){
        var currentGroupName = $(this).prop("name");       
        // remove selected state from other items
        targetRadioButtons.not(this).prop('checked', false);
    });
})

谢谢

var targetRadioButtons = $("input:radio").not("input:radio[name=lunch_desserts]").not("input:radio[name=lunch_fruitjuice]");

这可能有点丑陋,但它应该有效:

$("input:radio").not("input:radio[name=lunch_desserts]").not("input:radio[name=lunch_fruitjuice]").not(...)

您所要做的就是一个接一个地链接not()命令,不包括您想要的所有元素。

更好的方法是提供您想要处理类似类的所有无线电输入(例如 use_these_ones )。这样,该行将像这样简单:

var targetRadioButtons = $("input.use_these_ones")
如果要

从选择中排除某些单选按钮,则可能应该在要排除的单选按钮中添加一个类。喜欢这个:

.HTML

<div><input type="radio" name="lunch_desserts" class="exclude" value="Jello"/> Jello</div>
<div><input type="radio" name="lunch_desserts" value="Pudding"/> Pudding</div>
<div><input type="radio" name="lunch_desserts" class="exclude" value="Candy"/> Candy</div>
<div><input type="radio" name="lunch_fruitjuice" value="Apple Juice"/> Apple Juice</div>
<div><input type="radio" name="lunch_fruitjuice" class="exclude" value="Orange Juice"/> Orange Juice</div>
<div><input type="radio" name="lunch_fruitjuice" value="Guava Juice"/> Guava Juice</div>

JavaScript

// Select radio buttons that do not have the exclude class
var targetRadioButtons = $("input:radio:not(.exclude)");
// Test it by disabling just the targetRadioButtons
targetRadioButtons.attr("disabled", true);

演示:http://jsfiddle.net/J2DXF/

var exclude = ['lunch_fruitjuice', 'lunch_desserts'];
var targetRadioButtons = $("input:radio");
for (var i = 0; i < exclude .length; i++)
    targetRadioButtons = targetRadioButtons.not("input:radio[name="+exclude[i]+"]");