幾個月前我「學習」了JavaScript,但很快就拿起了Python並花費了過去幾個月用該語言編寫程序,所以我決定回去是個好主意實際上學習 JavaScript。現在我正在製作一個非常簡單的「博客」,其中帶有JS的帖子,從帖子生成哈希鏈接,並創建一個最近的帖子部分,您可以點擊鏈接跳轉到帖子這一頁。Javascript添加到新ID的ID和散列鏈接
例如,假設該職位之一的格式是這樣的:
<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示例 – samrap