【问题标题】:jquery change tagjquery 更改标签
【发布时间】:2011-11-14 20:38:27
【问题描述】:

我的这段代码不起作用,你能帮帮我吗?我希望我将 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>

【问题讨论】:

  • 您的示例中发生了什么? this 不会成为你的文件吗?

标签: javascript jquery tags


【解决方案1】:

“replaceWith()”调用中this 的值不会是“s7”元素;它将是 this 在更大的“document.ready”处理程序中的任何内容。

要做你想做的事,使用“.each()”:

  $('.s7').each(function() {
    $(this).replaceWith($('<h1>' + $(this).html() + '</h1>'));
  });

在那个版本中,jQuery 将为每个类为“s7”的元素调用“each”函数。此外,在该函数调用中,jQuery 安排 this 在每次迭代时引用其中一个 DOM 元素。

为了进一步详细说明差异,请考虑在我的版本和您的版本中,“replaceWith()”的参数是在“.replaceWith()”被调用之前计算的。也就是说,涉及$(this) 的字符串连接表达式在函数调用之前进行评估。因此,this 无法获取链中任何元素的值。 JavaScript 根本不能那样工作。

但是,通过“.each()”循环,我们可以确保this 具有有用的值。请注意,“.each()”将对当前 DOM 元素的引用作为显式参数传递,因此代码也可能如下所示:

  $('.s').each(function(index, element) {
    $(element).replaceWith($('<h1>' + $(element).html() + '</h1>'));
  });

【讨论】:

  • 你在最后缺少)
  • 哎呀,是的,我刚刚看到你的答案,正在检查我的答案:-) 谢谢!
【解决方案2】:

问题是您将所有元素与s7 类匹配,但是您需要一一处理它们以便将它们的内容复制到新元素中。在您当前的代码中,this 始终是 document,而不是当前元素。

您可以使用each() 来遍历匹配的元素:

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

或许:

$(".s7").each(function() {
    $("<h1>" + $(this).html() + "</h1>").replaceAll(this);
});

【讨论】:

    【解决方案3】:

    您缺少右括号,并且您在错误的上下文中使用了 this

    $(document).ready(function(){
        $(".s7").replaceWith($('<h1>' + $(".s7").html() + '</h1>'));
    });
    

    http://jsfiddle.net/L82PW/

    如果您有多个类名为s7 的元素,请使用.each()

    $(document).ready(function(){
        $(".s7").each(function(){
            $(this).replaceWith($('<h1>' + $(this).html() + '</h1>'));
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 2018-09-03
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多