2

我的代码中有一些可折叠的段,我使用 jQuery 实现了这些段。

像这样:

<h2 class="expand">Link1</h2>
                <div class="collapse">
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore 
                    et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip 
                    ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore 
                    eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa 
                    qui officia deserunt mollit anim id est laborum.</p>                
                    <p class="top"><a href="#content">Top of page</a></p>
                </div>

还有一些与上面的代码相同的部分。

当我单击它时,我想获取每个标题的 ID。比如说,当我单击“Link1”时,我希望它的 ID 弹出。

我已经定义了在弹出窗口中显示 id 的函数。这里是 :

 $(document).ready(function () {
        $("a").click(function (event) {
          alert(event.target.id);
        });
  });

每当我运行应用程序并单击(比如说)“Link1”时,我都会得到一个空白输出。为所有链接声明单独的类似乎是一种选择,但我想这样做。任何人都可以建议任何替代方法来获取这些元素的 Id 吗?

4

2 回答 2

6

您提供的标记表明您没有为这些元素提供 id。尝试给他们一个 ID,如下所示:

<a id="contentLink" href="#content">Top of page</a>

然后你可以这样做:

 $(document).ready(function () {
    $("a").click(function (event) {
        alert($(this).attr("id"));
    });
 });

编辑:或者当你说“ID”时,你实际上是指 href (因为你的标记有 href 属性),那么你可以这样做:

$(document).ready(function () {
    $("a").click(function (event) {
        alert($(this).attr("href"));
    });
 });
于 2012-05-08T11:24:56.140 回答
2

首先,this如果您指的是绑定处理程序的元素,则应该使用。考虑一下:

<a href="#content" id="a"><span id="b">foo</span></a>

a如果元素上绑定了处理程序,this.id则将是awhileevent.target.id将是b。除非你的意思是 event.target,使用this.

其次,id 值不是继承的(事实上,因为它们必须是唯一的,所以如果它们是唯一的,那就没有意义了)。您要么需要给a元素一个id值,要么需要遍历文档并找到相关元素以获取其id.

您可以使用如下代码执行此操作:

$(this).closest('div').prev().attr('id')

但是,您的h2 标签实际上没有id,因此您需要给它一个。如果要获取该标签的文本,请使用text

$(this).closest('div').prev().text()
于 2012-05-08T11:28:26.717 回答