将元素的文本用于父标题的 ID 值
Use an element's text for parent heading's ID value
在我的页面上,我有以下HTML:
<div class="Module-item"><!-- list -->
<div class="AnchorContainer" id="">
<h1>
<span class="InsertAsAnchor">Services</span>
</h1>
<div class="clear"></div>
</div>
</div>
HTML 片段是一个列表,因此在具有不同类型内容的页面上更常见。我想要的是这个:
jQuery(document).ready(function(){
//loop trough entire page .Module-item .AnchorContainer h1 span
//if span contains text, take value and use it as ID for h1, but this could also be H2,H3,H4,H5 and H6
//and if span contains text with spaces, remove the spaces so 'Our Services' becomes 'Ourservices'
});
我希望有人能告诉我如何以正确的方式做到这一点,
既然你是新来的,我就给你减点小调。试试这个:
$('.Module-item h1 > span, .Module-item h2 > span, .Module-item h3 > span')
.each(function() {
var myText = $(this).text().replace(' ','');
$(this).parent().attr('id', myText);
});
- http://api.jquery.com/each
- http://api.jquery.com/text
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
以后,请先
我就是这样做的。
http://jsfiddle.net/f7jhtd4x/
var moduleSpan = $('.module-item span');
$.each(moduleSpan, function(key, value){
var span = $(this);
if(span.text()) span.closest('.anchor-container').attr('id', span.text().replace(/ /g,''));
});
这应该可以做到:
$('.Module-item > .AnchorContainer').find('h1,h2,h3,h4,h5,h6').attr('id', function() {
var sp = $('>span:first', this);
if( sp.length === 1 || sp.text().trim().length > 0 ) {
return sp.text().trim().replace(/ /g,'');
}
});
$('.Module-item > .AnchorContainer').find('h1,h2,h3,h4,h5,h6').attr('id', function() {
var sp = $('>span:first', this);
if( sp.length === 1 || sp.text().trim().length > 0 ) {
return sp.text().trim().replace(/ /g,'');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="Module-item"><!-- list -->
<div class="AnchorContainer" id="">
<h1>
<span class="InsertAsAnchor"> Services </span>
</h1>
<h3>
<span class="InsertAsAnchor"></span>
</h3>
<h5>
<span class="InsertAsAnchor">Our Very Many Services </span>
</h5>
<h6>
<span class="InsertAsAnchor"> Their Services</span>
</h6>
<div class="clear"></div>
</div>
</div>
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 如何在给定 id 的情况下引用“标题”
- 根据类ID分配Fancybox标题
- 如果我知道按钮的 id,如何使用 javascript 设置 DOM 按钮的标题
- 从已知的视频 ID 获取 YouTube 视频标题
- 将元素的文本用于父标题的 ID 值
- 将 URL 设置为带有破折号而不是 ID 的 SEO 友好标题
- 在网址中使用文章标题,而不是 id
- 隐藏可滚动标题(HTML ID)
- 使用id获取面板的标题
- 为什么facebook会添加id="pageTitle"每个页面的标题
- 使汉堡包ID在两个标题中工作
- 如何在每个ID上更改标题的背景颜色
- 如何为标题的部分内容提供ID ?标签
- 打印youtube视频标题脚本仅提供视频ID
- 如何使用linqjs获得具有特定id的图书标题?
- 按id更改可折叠标题内的文本或显示图像
- 获得Youtube标题给定的id
- Wordpress中的条件标签:如何根据页面ID或标题运行不同的JS文件
- 使用Javascript更改多个id的标题,从原始值计算