[英]Change value of h2 to its text
我的问题是,我需要将 H2 的值更改为他自己的文本,但是我的代码将所有 H2s 的值更改为页面的第一个 H2 文本,而不是自己的文本。
$(function () { $('h2').attr('id', document.querySelector("h2").innerText); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script> <h2>Title 1</h2> <h2>Title 2</h2> <h2>Title 3</h2>
使用.attr()
的函数版本访问特定元素
const normaliseId = (val, delimiter = "-") => val.replace(/\s+/g, delimiter); $("h2").attr("id", function () { // each element in the collection can be referenced via `this` return normaliseId(this.textContent); }); console.log($("#container").html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script> <div id="container"> <h2>Title 1</h2> <h2>Title 2</h2> <h2>Title 3</h2> </div>
这在纯 JavaScript 中是完全可以实现的——因为你已经在使用它了——使用以下方法:
// using document.querySelectorAll() to retrieve all <h2> elements in the document, // and then passing that NodeList to NodeList.prototype.forEach() to iterate over // that NodeList: document.querySelectorAll('h2').forEach( // using an anonymous Arrow function on each node of the NodeList, // wherein we assign the text-content of the current <h2> element - // after first replacing all strings of white-space with the '-' // character to the 'id' property: (title) => title.id = title.textContent.replace(/\s+/g, '-') );
h2::after { background-color: gainsboro; color: honeydew; display: block; font-size: 0.8em; content: '(#' attr(id) ')'; );
<h2>Title 1</h2> <h2>Title 2</h2> <h2>Title 3</h2>
如果您更喜欢使用 jQuery,那么当然也可以使用以下方法:
// we select all <h2> elements in the document, and chain the // collection with the prop() method to update the named ('id') // property of the current element in the collection: $('h2').prop('id', function() { // here we retrieve the text of the current element, // use String.prototype.replace() to replace all white- // space characters (\s+) with the '-' character: return $(this).text().replace(/\s+/g, '-'); });
h2::after { background-color: gainsboro; color: honeydew; content: '(#' attr(id) ')'; display: block; font-size: 0.8em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2>Title 1</h2> <h2>Title 2</h2> <h2>Title 3</h2>
您自己的代码的问题:
$(function () {
$('h2').attr('id', document.querySelector("h2").innerText);
});
是否document.querySelector()
仅返回document
中与提供的 CSS 选择器匹配的第一个元素(如果有),这就是为什么每个<h2>
都被分配了相同的id
,即第一个<h2>
。
还值得指出的是id
不能包含空格; 它必须是一个单一的字母数字字符串。
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.