【发布时间】:2013-12-13 14:16:04
【问题描述】:
几个月前我“学习”了 JavaScript,但很快就学会了 Python,并在过去几个月里用该语言编写程序,所以我决定回去真正学习 JavaScript。现在我正在用 JS 制作一个非常简单的“博客”,它获取帖子的标题,从帖子中生成一个哈希链接,并创建一个 recent posts 部分,您可以在其中单击链接到跳转到页面中的帖子。
例如,假设其中一篇文章的格式如下:
<h2 class="post">Another post for you</h2>
<h4>I know you love these</h4>
有多个帖子,底部有一个空容器,用于附加最近的帖子链接:
<div id="get-post"></div>
我的 JS 代码基本上使用 post 类获取每个标题,并从元素的标题创建一个哈希链接(删除空格和逗号)。然后它创建并附加一个包含帖子标题的文本节点,然后将整个链接附加到get-post 容器中。
var postList = $('#get-post');
var post = $('.post');
function generateRecentPosts() {
post.each(function() {
// Create link from post title that will be used to
// access that post.
var postLink = document.createElement('a');
// Create text node from post title that will be appended
// to the postLink.
var text = document.createTextNode($(this).html());
// Add elements to the DOM.
postLink.href = createLocalLink($(this));
postLink.appendChild(text);
postList.append(postLink);
postList.append('<br />');
});
}
function createLocalLink(elm) {
// Creates the href link that will be used to go to a blog post.
// For example, if the title of the elm parameter is "My Post",
// a link is created called #My-Post that will be used to access
// that post.
elm.id = elm.html().replace(/,/g, '').replace(/\s/g, '-');
console.log(elm.id); // Make sure the ID is added.
return '#' + elm.id;
}
generateRecentPosts();
我的问题是它生成的链接不指向为每个标题创建的 ID。当我点击链接时,我可以看到它成功创建了 href 哈希 #My-Post 并将其添加到锚标记中,但它并没有将我带到帖子标题。
示例:http://jsfiddle.net/samrap/GQtxL/
我什至添加了一个控制台日志功能,以确保将 ID 添加到标题中,因为我认为这是问题所在,但这并不是因为控制台正在打印正确的新 ID。我真的可以使用一些帮助来找出问题所在。
【问题讨论】:
-
请发布一个附加的帖子示例及其相应的链接,此外,您可能应该使用
text()而不是html()来生成id,以避免可能插入特殊字符 -
添加了一个带有 text() 函数的 jsfiddle 示例
标签: javascript jquery html dynamic