为此javascript添加多个排除项

时间:2013-10-29 14:53:45

标签: javascript

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

我也想排除“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);
    });
})

由于

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

这可能有点难看,但应该有效:

$("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")

答案 2 :(得分:0)

如果要从选择中排除某些单选按钮,则应该将类添加到要排除的单选按钮中。像这样:

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/

答案 3 :(得分:0)

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