在我的页面上,我有以下HTML:
<div class="Module-item"><!-- list -->
<div class="AnchorContainer" id="">
<h1>
<span class="InsertAsAnchor">Services</span>
</h1>
<div class="clear"></div>
</div>
</div>
HTML piece是一个列表,因此在具有不同类型内容的页面上更常见。 我想要的是这个:
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'
});
我希望有人能告诉我如何以正确的方式做到这一点,
答案 0 :(得分:3)
既然你是新人,我会给你一些懈怠。试试这个:
$('.Module-item h1 > span, .Module-item h2 > span, .Module-item h3 > span')
.each(function() {
var myText = $(this).text().replace(' ','');
$(this).parent().attr('id', myText);
});
将来,请先解决这个问题。
答案 1 :(得分:0)
这就是我做到的。
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,''));
});
答案 2 :(得分:0)
这应该这样做:
$('.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,'');
}
});
&#13;
<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>
&#13;