jquery simple swap p element?
Given a p element like so:
<p>Something</p>
I want to, when the user mouses over it, we have, instead <p>&l开发者_开发知识库t;a href="blabla.org">go here</a></p>
After hovering if the mouse leaves the p area, return to the previous:
<p>Something</p>
state.
Can I have a simple example of something like this?
Thanks a lot, MEM
Or a simple modification of Ken Redler's original that uses .data()
to keep track of things:
$('p#someID').hover(
function() {
var $this = $(this);
$this.data('orig', $this.html()).html('<a href="blabla.org">go here</a>');
},
function() {
var $this = $(this);
$this.html($this.data('orig')).removeData('orig');
}
);
http://www.jsfiddle.net/ambiguous/FhET2/1/
Updated: As @Phrogz points out, I missed part of the sense of the question. The suggestions of capturing state with a closure or using data()
are good ones, but here's another way (with an amusing number of moving parts):
$(document).ready( function(){
$('p#someID').hover(
function() { // on mouseEnter
$(this)
.contents()
.wrap('<span class="hide"/>') // wrap 'n' hide
.end() // back to 'this'
.append('<a href="blabla.org">Fascinating Link!</a>'); // add link
}, function() { // on mouseLeave
$(this)
.find('a')
.remove() // kill the anchor
.end() // back to 'this'
.find('span.hide') // the wrapper
.contents() // the wrapped
.unwrap(); // kill the wrapper, leaving its contents
});
});
This assumes a style like so:
span.hide {
display: none;
}
Updated example: http://www.jsfiddle.net/redler/HAGzH/1/
$('p#IDHERE').hover(
function(){ // on mouseEnter
$(this).contents().replaceWith('<a href="blabla.org">go here</a>');
},
function(){ // on mouseLeave
$(this).contents().replaceWith("something");
}
);
This will replace all text
精彩评论