Combining .hover() and .replaceWith()
I can't get this simple .replaceWith()
to co-operate with a .hover()
. Would appreciate some help.
I want it the text to change to EXPAND when I hover on it, and go back to SHOWS when I mouseout. I can get the text to change to EXPAND, but I can't get the text to go back to the original, SHOWS.
The JSFiddle code for anyone kind enough to have a look.
$(document).ready(function() {
$("p").hover(
function () {
$('#shows').replaceWith('<h2>Expand&l开发者_JAVA百科t;/h2>');
},
function () {
$('#shows').replaceWith('<h2>Shows</h2>');
}
);
});
The problem is when you're replacing it it's losing the id
attribute. So although the mouseout
function of the hover()
event fires it can't find the element #shows
.
Try this instead:
// Change H1 text to "EXPAND" when hovered on, and go *back* to "SHOWS" when the mouse leaves
$(document).ready(function() {
$("p").hover(
function () {
$('#shows').text('Expand');
},
function () {
$('#shows').text('Shows');
}
);
});
You should always use .text()
or .html()
in examples like this because acctually all you want to do is change the inner bit the TEXT or the HTML contained within the <h2>
tag, rather than the whole element.
If you want to use replaceWith:
$(document).ready(function() {
$("p").hover(
function () {
$('#shows').replaceWith('<h2 id="shows">Expand</h2>');
},
function () {
$('#shows').text('<h2 id="shows">Shows</h2>');
}
);
});
.replaceWith() will replace the original element (#shows
) entirely --> no more element with id=#shows
will be found (2nd try will fail).
What you want to do, is replace the inner html of #shows
(using .html()):
$(document).ready(function() {
$("p").hover(
function () {
$('#shows').html('<h2>Expand</h2>');
},
function () {
$('#shows').html('<h2>Shows</h2>');
}
);
});
once you use .replaceWith()
method, the element #shows
no longer exists and cannot be replaced anymore :)
精彩评论