jquery更改标记

Ira*_*kli 4 javascript tags 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>
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 6

问题是你要将所有元素与类匹配s7,但是你需要逐个处理它们才能将它们的内容复制到新元素中.在您当前的代码中,this始终document不是当前元素.

您可以使用each()迭代匹配的元素:

$(".s7").each(function() {
    var $this = $(this);
    $this.replaceWith($("<h1>" + $this.html() + "</h1>"));
});
Run Code Online (Sandbox Code Playgroud)

或者可能:

$(".s7").each(function() {
    $("<h1>" + $(this).html() + "</h1>").replaceAll(this);
});
Run Code Online (Sandbox Code Playgroud)