gpt4 book ai didi

javascript - 使用 .replaceWith 更改 dom

转载 作者:行者123 更新时间:2023-11-28 11:22:34 25 4
gpt4 key购买 nike

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

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

最佳答案

我建议直接使用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>

引用文献:

关于javascript - 使用 .replaceWith 更改 dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com