在多个输入上简化类似的更改事件处理程序

时间:2022-10-20 11:45:38

How can I write this functions more generally. So I don't have to repeat this over and over again?

我怎样才能更一般地编写这个函数。所以我不必一遍又一遍地重复这个?

jQuery("input[name='option1']").change(function () {
    $("#option1").addClass('highlight');
    setTimeout(function () {
        $("#option1").removeClass("highlight");
    }, 100);
});

jQuery("input[name='option2']").change(function () {
    $("#option2").addClass('highlight');
    setTimeout(function () {
        $("#option2").removeClass("highlight");
    }, 100);
});

jQuery("input[name='optionX']").change(function () {
    $("#optionX").addClass('highlight');
    setTimeout(function () {
        $("#optionX").removeClass("highlight");
    }, 100);
});

2 个解决方案

#1


2  

You can use attribute starts with selector to bind the event on all the <input> elements whose name starts with option.

您可以使用带有选择器的属性启动来绑定名称以option开头的所有元素上的事件。

// Bind change event on all the `<input>` elements whose `name` attribute starts with `option`.
$('input[name^="option"]').change(function () {
    // Get the `name` of this element
    var name = $(this).attr('name'),
        elem = $('#' + name); // Get the corresponding element whose id is same as the name of this element

    elem.addClass('highlight');
    setTimeout(function () {
        // Use cached element object
        elem.removeClass('highlight');
    }, 100);
});

#2


0  

You can try this:

你可以试试这个:

//I would rather use a class instead of just input but anyhow...
$('input').change(function(){
    var elem_name = $(this).attr('name');
    $('#'+elem_name ).addClass('highlight');
    setTimeout(function () {
        $('#'+elem_name).removeClass('highlight');
    }, 100);
});

#1


2  

You can use attribute starts with selector to bind the event on all the <input> elements whose name starts with option.

您可以使用带有选择器的属性启动来绑定名称以option开头的所有元素上的事件。

// Bind change event on all the `<input>` elements whose `name` attribute starts with `option`.
$('input[name^="option"]').change(function () {
    // Get the `name` of this element
    var name = $(this).attr('name'),
        elem = $('#' + name); // Get the corresponding element whose id is same as the name of this element

    elem.addClass('highlight');
    setTimeout(function () {
        // Use cached element object
        elem.removeClass('highlight');
    }, 100);
});

#2


0  

You can try this:

你可以试试这个:

//I would rather use a class instead of just input but anyhow...
$('input').change(function(){
    var elem_name = $(this).attr('name');
    $('#'+elem_name ).addClass('highlight');
    setTimeout(function () {
        $('#'+elem_name).removeClass('highlight');
    }, 100);
});