I am working through the jQuery documentation and found a piece of a replaceWith() example (the last example from http://api.jquery.com/replaceWith/) that I don't fully understand. I will post a link to this post as a comment on the jQuery documentation replaceWith() page to aid others new to jQuery and DOM manipulation.
Specifically, I do not fully understand the behavior of "$container" in:
"$("p").append( $container.attr("class"开发者_Python百科) );"
I was expecting the above code to append the word "inner" to the "p" contents because the "replaceWith()" method was called when the variable was created:
var $container = $("div.container").replaceWith(function() {
return $(this).contents();
});
However, "$("p").append( $container.attr("class") );" actually appends the word "container", not the word "inner".
It seems that the variable "$container" actually references the div that was replaced, "$("div.container")", not the replacing content, "$(this).contents();".
Two questions:
- What is "replaceWith()" doing in this context?
- Is there something special going on with the order of operations or the "attr()" method that I am not seeing?
Here is the full code:
<!DOCTYPE html>
<html>
<head>
<style>
.container { background-color: #991; }
.inner { color: #911; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>
<button>Replace!</button>
</p>
<div class="container">
<div class="inner">Scooby</div>
<div class="inner">Dooby</div>
<div class="inner">Doo</div>
</div>
<script>
$('button').bind("click", function() {
**var $container = $("div.container").replaceWith(function() {
return $(this).contents();
});**
**$("p").append( $container.attr("class") );**
});
</script>
</body>
</html>
From the .replaceWith()
documentation:
The
.replaceWith()
method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.
...so what you're seeing is the expected behavior, $container
should and does refer to what was replaced, not the replacement.
精彩评论