使用 .replaceWith 更改 dom

Change a dom using .replaceWith

我有一些代码几乎完全符合我的要求。它将所有强标签更改为样式化的 h3 标签,这是完美的,但对于我的生活,我无法弄清楚用什么替换“.click”以使其自动成为 运行。我试过“.ready”,它在我的 jquery.

中给了我一个错误
$(document).ready(function(){
    $('strong').click(function(){
        $(this).replaceWith($('<h3 style="margin:0px;display:inline;">' + this.innerHTML + '</h3>'))
    })
});

您想使用 each() 以便它遍历所有这些。

$('strong').each(function(){ ... });

您正在做的是向页面上的所有 <strong> 元素添加一个处理程序,只要单击其中一个元素就会触发该处理程序。如果您想在文档准备好后立即执行替换,试试这个:

$(document).on('ready', function () {
    $('strong').each(function () {
        $(this).replaceWith($('<h3 style="margin:0px;display:inline;">' + this.innerHTML + '</h3>'));
    });
});

这应该可以做到。

$(document).ready(function(){
    $('strong').each(function(){
        $(this).replaceWith($('<h3 style="margin:0px;display:inline;">' + this.innerHTML + '</h3>'))
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong>1</strong>
<strong>2</strong>
<strong>3</strong>

我建议直接去 replaceWith():

// most (if not all) jQuery methods iterate over
// the collection to which they're chained:
$('strong').replaceWith(function () {

  // here 'this' is the individual <strong> element over
  // which the method iterates, and we return the created element:
  return $('<h3 style="margin:0px;display:inline;">' + this.innerHTML + '</h3>');
});

$('strong').replaceWith(function () {
  return $('<h3 style="margin:0px;display:inline;">' + this.innerHTML + '</h3>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong>1</strong>
<strong>2</strong>
<strong>3</strong>
<strong>4</strong>

顺便说一下,在普通的 JavaScript 中,这也很容易实现:

// creating a <h2> element:
var heading = document.createElement('h2'),
// initialising an empty variable:
  clone;

// setting the display and margin properties:
heading.style.display = 'inline';
heading.style.margin = '0';

// using Function.prototype.call() to use
// Array.prototype.forEach() on the array-like
// NodeList returned by document.querySelector():
Array.prototype.forEach.call(document.querySelectorAll('strong'), function(bold) {

  // cloning the created <h2> element:
  clone = heading.cloneNode();

  // setting its innerHTML:
  clone.innerHTML = bold.innerHTML;

  // traversing to the parentNode, and
  // using Node.replaceChild() to replace
  // existing <strong> element with the
  // cloned <h2> element:
  bold.parentNode.replaceChild(clone, bold);
});

var heading = document.createElement('h2'),
  clone;

heading.style.display = 'inline';
heading.style.margin = '0';

Array.prototype.forEach.call(document.querySelectorAll('strong'), function(bold) {

  clone = heading.cloneNode();

  clone.innerHTML = bold.innerHTML;

  bold.parentNode.replaceChild(clone, bold);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong>1</strong>
<strong>2</strong>
<strong>3</strong>
<strong>4</strong>

参考文献: