简体   繁体   中英

jQuery highlight matched elements with live() or on()

in my jsFiddle example can you see that I made a button where I add some elements and links to delete this elements. In this example it is not about going to delete the elements, but to hover the (remove)link made by clicking the button so it highlights the element with the same "number" attribute.

I have tried to use live(); and on(); for it, but it does not do anything, because the items are made after building the page.

I prefer to use on(); now because jQuery says:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

My jQuery code:

    function numbers() {
        return $('#links span').length;
    }

    $('#add').on('click', function () {
        $('#links').append('<span number="' + (numbers() + 1) + '">Remove element ' + (numbers() + 1) + '</span><br />');
        $('#elements').append('<div number="' + numbers() + '" class="element">Element ' + numbers() + '</div>');
    });

    $('#links span').live('hover', function () {
        var number = $(this).attr('number');
        if ($('#elements .element').attr('number') == number) {
            $(this).addClass('highlight');
        }

});

First of all, you should dynamically bind the events, since the elements are added dynamically. Second of all, you should make use of mouseenter and mouseleave events, since you want to toggle the highlighting and need to know when the cursor is leaving the element. And third of all I recommend using data- -attributes instead of a custom attribute called number .

function numbers() {
    return $("#links span").length;
}

$("#add").on("click", function () {
    var number = numbers() + 1;
    $("#links").append("<span data-number='" + number + "'>Remove element " + number + "</span><br />");
    $("#elements").append("<div data-number='" + number + "' class='element'>Element " + number + "</div>");
});

// Dynamically bind mouseenter and mouseleave events, so they also apply to dynamically added elements
$("body").on("mouseenter", "#links span", function () {
    var number = $(this).data("number");
    $(".element[data-number='" + number + "']").addClass("highlight");
}).on("mouseleave", "#links span", function () {
    var number = $(this).data("number");
    $(".element[data-number='" + number + "']").removeClass("highlight");
});

FIDDLE

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