问题
I have this code that doesn't work, can you help me? I want that I changed tag name "p" of class="s7" to "h1"
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".s7").replaceWith($('<h1>' + $(this).html() + '</h1>');
});
</script>
回答1:
The problem is that you're matching all the elements with class s7
, but you need to process them one by one in order to copy their content into new elements. In your current code, this
is always document
, not the current element.
You can use each() to iterate over the matched elements:
$(".s7").each(function() {
var $this = $(this);
$this.replaceWith($("<h1>" + $this.html() + "</h1>"));
});
Or maybe:
$(".s7").each(function() {
$("<h1>" + $(this).html() + "</h1>").replaceAll(this);
});
回答2:
You're missing a closing parenthesis, and you're using this in the wrong context:
$(document).ready(function(){
$(".s7").replaceWith($('<h1>' + $(".s7").html() + '</h1>'));
});
http://jsfiddle.net/L82PW/
If you have multiple elements with a class name of s7
, use .each()
:
$(document).ready(function(){
$(".s7").each(function(){
$(this).replaceWith($('<h1>' + $(this).html() + '</h1>'));
});
});
回答3:
The value of this
in your "replaceWith()" call is not going to be the "s7" element; it's going to be whatever this
is in the greater "document.ready" handler.
To do what you want, use ".each()":
$('.s7').each(function() {
$(this).replaceWith($('<h1>' + $(this).html() + '</h1>'));
});
With that version, jQuery will call the "each" function for each element with class "s7". Inside that function call, furthermore, jQuery arranges for this
to refer to one of those DOM elements on each iteration.
To further elaborate the difference, consider that in both my version and yours the argument to "replaceWith()" is computed before ".replaceWith()" is called. That is, the string concatenation expression involving $(this)
is evaluated before the function call. Thus, there's just no way for this
to take on the value of any element in the chain; JavaScript simply does not work that way.
With the ".each()" loop, however, we can ensure that this
has a useful value. Note that ".each()" also passes a reference to the current DOM element as an explicit parameter, so the code could also look like:
$('.s').each(function(index, element) {
$(element).replaceWith($('<h1>' + $(element).html() + '</h1>'));
});
来源:https://stackoverflow.com/questions/7380137/jquery-change-tag