【问题标题】:Javascript add ID and hash link to new IDJavascript 将 ID 和哈希链接添加到新 ID
【发布时间】: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


【解决方案1】:

您的h2 标签需要有一个与链接对应的idname 属性,这就是内部链接起作用的原因。 id 没有被添加,因为您正在访问一个 jQuery 对象,就好像它是一个 DOM 节点 (elm.id = ...)。修改 createLocalLink 函数以使用 jQuery 的 attr 方法设置 id 属性:

elm.attr('id', elm.html().replace(/,/g, '').replace(/\s/g, '-'));

此外,由于您可以使用 jQuery,您可以将代码缩减为:

var $this = $(this),
    link = createLocalLink($this);

var $postLink = $('a', {
    text: $this.text(),
    href: link
})

postList.append($postLink).append('<br />');

这是你的小提琴更新:http://jsfiddle.net/GQtxL/1/

【讨论】:

  • 这就是我认为我在createLocalLink():elm.id = elm.html().replace(/,/g, '').replace(/\s/g, '-'); 的这一行中所做的?
  • 看到了问题,更新了我的答案。你使用的是.id,应该是attr('id', ...)
  • 谢谢你,另外,我读到使用 jq 创建元素的速度较慢,有很大不同吗?
  • 它并不慢,实际上可以更快,具体取决于您用于创建元素的操作和方法(主要是因为 jQuery 使用 createDocumentFragment 来最小化回流 (developer.mozilla.org/en-US/docs/Web/API/…)
  • 因为 jQuery 不返回 DOM 节点(这将适用),它返回对 jQuery 对象的引用,该对象将接受 id 属性但不会将其绑定到 DOM 节点(s) 它包含。可以使用$(selector).get(0)$(selector)[0]直接访问DOM节点
【解决方案2】:

这是因为您的链接使用了 href = "#My-Post",但没有任何帖子的 ID 为“My-Post”。它只有一个类“帖子”。

发生这种情况是因为您传递给 createLocalLink() 函数的参数是一个 DOM 节点。但是通过执行 elm.id 您不会更改 DOM 属性,而是将另一个属性添加到“elm”对象。因此,您的“榆树”对象是

x.fn.x.init[1]
0: h2.post
context: h2.post
id: "Another-post-for-you"
length: 1
__proto__: Object[0]

因此,实际的帖子永远不会获得属性 ID,只有“elm”对象才能获得它。注意下面的空 ID 属性

draggable: false
firstChild: text
firstElementChild: null
hidden: false
id: ""
innerHTML: "Another post for you"
innerText: "Another post for you"

因此,您的文档没有 ID 为“My-Post”的元素。您可以查看 HTML 的源代码来验证这一点。

要使内部链接正常工作,应该有一个 ID 与链接的 href 属性中使用的 ID 相同的元素。

例如

<div id="post1">
 Your Post Here
</div>

<!--just to show the effect of moving to the post-->
<div style="clear:both; height:900px"></div>

<a href = "#post1">Click Here</a>

这会起作用,因为有一个 id 为“post1”的元素,并且链接使用了将其链接到相应元素的 href“#post1”。因此,请将相应的 id 添加到您的帖子中(除了您的链接)以使其正常工作。

【讨论】:

  • 这就是我认为我在createLocalLink():elm.id = elm.html().replace(/,/g, '').replace(/\s/g, '-'); 的这一行中所做的?
【解决方案3】:

在函数createLocalLink 中,您使用elm 参数作为dom 节点,但实际上将一个jQuery 包装对象传递给它,它没有id 属性。要使其正常工作,请使用 elm.get(0).id = ...elm.attr('id', elm.text().replace(/,/g, '').replace(/\s/g, '-'););

【讨论】:

    猜你喜欢
    • 2017-10-24
    • 2019-04-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多