简体   繁体   中英

Combining two change functions

How do I combine these two different uses of .change to make one function?

Both are using $('input[name="menu"]') but are semantically different so I am not sure the proper way to combine the two.

I tried putting $(".menu[data-id=" + this.id + "]").toggleClass("active", this.checked); inside of the .on("change"), function () without any luck.

 $('input[name="menu"]') .change(function() { $(".menu[data-id=" + this.id + "]").toggleClass("active", this.checked); }) .change(); $(function() { $('input[name="menu"]').on("change", function() { if ( $(this) .closest('[class*="list-"]') .is(".list-custom") ) { if ($(this).is(":checked")) { $(this) .siblings("[data-icon]") .attr("data-prefix", "fas") .closest(".launch-icon") .addClass("checked"); } else { $(this) .siblings("[data-icon]") .attr("data-prefix", "far") .closest(".launch-icon") .removeClass("checked"); } } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

If it was me, i will merge your code like this, but if you are searching for a real solution to your problems, please include the html markup and a code snippet that works.

// Starting point.

$(document).ready(function()
{
    // Register listener for the change event.

    $('input[name="menu"]').change(function()
    {
        // This was on the first listener of change event.

        $(".menu[data-id=" + this.id + "]").toggleClass("active", this.checked);

        // This was on the second listener of change event.

        if ($(this).closest('[class*="list-"]').is(".list-custom"))
        {
            if ($(this).is(":checked"))
            {
                $(this).siblings("[data-icon]").attr("data-prefix", "fas")
                       .closest(".launch-icon").addClass("checked");
            }
            else
            {
                $(this).siblings("[data-icon]").attr("data-prefix", "far")
                       .closest(".launch-icon").removeClass("checked");
            }
        }
    });

    // Trigger a change event on the input element.
    // This was after the first event listener (why?)

    $('input[name="menu"]').change();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM