jquery 改变标签
我的代码不起作用,你能帮我吗?我希望将 class="s7" 的标签名称“p”更改为“h1”
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".s7").replaceWith($('<h1>' + $(this).html() + '</h1>');
});
</script>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是您将所有元素与类
s7
进行匹配,但您需要一一处理它们,以便将其内容复制到新元素中。在当前代码中,this
始终是document
,而不是当前元素。您可以使用 each() 迭代匹配的元素:
或者也许:
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 alwaysdocument
, not the current element.You can use each() to iterate over the matched elements:
Or maybe:
您缺少右括号,并且在错误的上下文中使用了this:
http: //jsfiddle.net/L82PW/
如果您有多个类名为
s7
的元素,请使用.each()
:You're missing a closing parenthesis, and you're using this in the wrong context:
http://jsfiddle.net/L82PW/
If you have multiple elements with a class name of
s7
, use.each()
:“replaceWith()”调用中
this
的值不会是“s7”元素;它将是更大的“document.ready”处理程序中的任何this
。要执行您想要的操作,请使用“.each()”:
在该版本中,jQuery 将为每个具有“s7”类的元素调用“each”函数。此外,在该函数调用中,jQuery 安排
this
在每次迭代中引用这些 DOM 元素之一。为了进一步阐述差异,请考虑在我的版本和您的版本中,“replaceWith()”的参数都是在调用“.replaceWith()”之前计算的。也就是说,涉及
$(this)
的字符串连接表达式在函数调用之前进行计算。因此,this
无法获取链中任何元素的值; JavaScript 根本就不是这样工作的。然而,通过“.each()”循环,我们可以确保
this
具有有用的值。请注意,“.each()”还将当前 DOM 元素的引用作为显式参数传递,因此代码也可能类似于:The value of
this
in your "replaceWith()" call is not going to be the "s7" element; it's going to be whateverthis
is in the greater "document.ready" handler.To do what you want, use ".each()":
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 forthis
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: