基于事件在循环中隐藏元素

Hiding element in loop based on event

本文关键字:循环 隐藏 元素 于事件 事件      更新时间:2023-09-26

在我的表格中,我有五个类似的无线电组:

<label class="radio-inline"><input type="radio" name="persontype1" value="fo" checked="checked">FO</label>
<label class="radio-inline"><input type="radio" name="persontype1" value="po">PO</label>

然后我有一个循环来隐藏/显示其他元素,基于这些单选按钮的更改事件:

for (i = 1; i <= 5; i++) {
    $("input[type=radio][name=persontype" + i + "]").change(function() {
        if (this.value == 'fo') {
            $("#person-name" + i).removeClass('hidden');
        }
        else if (this.value == 'po') {
            $("#person-name" + i).addClass('hidden');
        }
    });
}

问题是它不是这样工作的。当我在选择器中使用绝对ID值名称时,它起作用:

$("#person-name1").addClass('hidden');

我尝试过使用一些全局变量,但也不起作用。有没有办法将变量i传递给该函数?

提前感谢JiKra

将代码封装在一个封闭的IIFE(立即调用的函数表达式)中:

for (i = 1; i <= 5; i++) {
    (function(i){
        $("input[type=radio][name=persontype" + i + "]").change(function() {
            if (this.value == 'fo') {
                $("#person-name" + i).removeClass('hidden');
            }
            else if (this.value == 'po') {
                $("#person-name" + i).addClass('hidden');
            }
        });
    })(i);
}

这将为内部i(函数的参数)提供一个函数范围。

不过,使用单个事件处理程序并具有属性来确定哪个是哪个更有意义:)

 // Match on starts-with "persontype" using ^=
 $("input[type=radio][name^=persontype]").change(function() {
     var target = $(this).data('target');
     // Do something to the target
 });