问题描述:

I have a simple set of jQuery statements for a particular class:

$(".printersToggle").mouseover(function() {

$(this).addClass("printersToggleOver");

});

$(".printersToggle").mouseout(function() {

$(this).removeClass("printersToggleOver");

});

and:

$(".printersToggle").click(function() {

var id = $(this).attr('id');

$.getJSON("/ajax",

function(data) {

$.each(data, function(key, val) {

$("#" + id).replaceWith('<div class="row printersToggle" id="' + id '"><div class="twelve columns">Show printers (Best price: £4.65)</div></div><!-- end of printers toggle --><!-- printers --><div class="row" id="printers"><table><thead><tr><th>Title</th><th>Rating (%)</th><th>Experience (jobs)</th><th>Average job speed (days)</th><th>Reliability (%)</th><th>Cost</th><th>Print</th></tr></thead><tbody><tr><td id="printersName_{{ design.id }}"></td><td id="printersRating"></td><td>4</td><td>2</td><td>96</td><td>£4.56</td><td class="success printButton radius">Add to Cart</td></tr></tbody></table></div>');

});

});

});

});

Without the second one (the click function), the first works as intended. With the second statement, the mouseover effects stop working. Any idea what's going on here?

网友答案:

When you call replaceWith(), you are removing the previous DOM element along with any event handlers associated with it. You should use on() with a selector to bind the event handler dynamically:

$('#parentContainer').on('mouseover', '.printersToggle', function() { ... });
网友答案:

use this code instead:

$("body").on("mouseover",".printersToggle" ,function(){$(this).addClass("printersToggleOver");
});


$("body").on("mouseout",".printersToggle" ,function(){$(this).removeClass("printersToggleOver");
});
网友答案:

You can use the .hover() function, see if that helps

$(".printersToggle").hover(function() { 
    $(this).addClass("printersToggleOver");
}, 
function() { 
    $(this).removeClass("printersToggleOver");
});
网友答案:

Have you tried using hover instead of mouseover / mouseout?

$(".printersToggle").hover(function() { 
    $(this).addClass("printersToggleOver");
}, function() { 
    $(this).removeClass("printersToggleOver");
});
网友答案:

Try:

$(document).ready(function () {
$(".printersToggle").hover(function() { 
        $(this).toggleClass("printersToggleOver");
    });
}); 
相关阅读:
Top