jQuery somehow adding spaces to output
I am trying to create a script to dynamically create anchor tags and links to a specific element. Howeve开发者_StackOverflow社区r, when I output the anchor text, it adds a bunch of spaces between the hash and the text.
$(document).ready(function(){
$('.accordion h2').each(function(){
var thisText = $(this).text();
var anchorText = thisText.replace(/ /g, "-");
var anchorLink = '<a name="' + anchorText + '"></a>';
var anchorTextFull = '<a href="#' + anchorText + '">' + thisText + '</a>';
$(this).before(anchorLink);
$(this).after(anchorTextFull);
});
});
This code outputs the following for the anchorTextFull variable:
<a href="# foo-bar">Foo Bar</a>
Where are these spaces coming from?
Thanks
jQuery includes a trim function that you can use to remove extra whitespace at the beginning or end of a string:
var thisText = $.trim($(this).text());
This problem is actually caused by HTML behaving differently then JQuery. In HTML, spaces and extra lines don't matter.
In HTML, these 2 examples are visually the same when rendered to the page:
<div id="vendor">Barracuda</div>
and
<div id="vendor">
Barracuda
</div>
However when you use JQuery's .Text() method, they yield different results.
<div id="vendor">Barracuda</div>
$('#vendor').text() // equals "Barracuda"
But this is very different:
<div id="vendor">
Barracuda
</div>
$('#vendor').text() // equals " Barracuda "
Thus the need to .trim() the results if you can't tailor the HTML, or just want to play it safe.
var thisText = $.trim($(this).text());
JSFiddle Working Example
These are probably coming from the $(this).text()
. These could be the new line characters within h2
tags. Do an alert("'" + $(this).text() + "'" )
to confirm.
精彩评论