根据标题名称动态地添加ID到标题?
问题描述:
我正在使用Jquery进行一个小型项目,并且遇到了问题。根据标题名称动态地添加ID到标题?
我试图创建一个小的脚本,将看一个页面,并自动分配基础上的标题文字的ID,以H1标题,即:
<h1> This is a Test </h1>
到
<h1 id="This_is_a_Test"> This is a Test</h1>
我已经能够选择每个H1,但是我还没有能够根据标题文本修改ID。
var $headers = $('.body h1);
$headers.attr("id", not sure exactly how to pass headers text to this?);
我明显是一个新手,但会感谢一些帮助! 谢谢!
答
使用jQuery的.attr()
与callback option读取头的文本,将其转换为蛇的情况下,并设置其为id
:
var $headers = $('.body h1');
$headers.attr("id", function() {
return $(this)
.text() // get the h1 text
.trim() // remove spaces from start and the end
.toLowerCase() // optional
.replace(/\s/g, '_'); // convert all spaces to underscores
});
console.log($headers[0]);
console.log($headers[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
<h1>This is a Test </h1>
<h1>This is a another Test </h1>
</div>
答
首先,您需要通过使用text
方法生成id
h1
。
var $headers = $('.body h1'); // select the element
var text = $headers.text(); // get the text of the element
var id = text.trim().split(' ').join('_'); // split by space and join using _
$headers.attr("id", id);
答
如果您想要为您页面中的每个h1
元素执行此操作,您可以执行类似操作:
$(function() {
$('h1').each(function() {
$(this).attr('id', $(this).text().replace(/ /g, '_'))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Some text</h1>
<h1>Some other text</h1>
功能将采取一切h1
元件,for each它将设置id
属性(使用attr
function)的该h1
元件的text()
的值(同时改变以下划线每空间)。
谢谢Ori!这对我来说非常合适,评论帮助我消化正在发生的事情。我非常感谢你的帮助! –