【问题标题】:click on photo and show corresponding item in list单击照片并在列表中显示相应的项目
【发布时间】:2016-06-02 19:12:10
【问题描述】:

我正在为我所在大学的数学系编写一个新网站。在编写包含我们教授信息的页面时,我遇到了一个问题。我设计了一张包含他们照片的表格,我的想法是当用户点击他/她的照片时,向用户展示一个包含有关该特定教授的更多详细信息的框。以下是 html 中 info-div 的外观:

div 包含有关教授的所有信息框

<div id = "kartenliste">

<div class="w3-card-4 visitenkarte hidden" id="visprof1">
    *info about the first professor*
</div>

</div>

这是我在 jQuery 中尝试过的:

$("#proftable td").click(function() {
    var itemIndex = $("#profdiv").index(this) + 1;      
    $("#kartenliste .visitenkarte:nth-child(itemIndex)").show();
});

所以我试图获取表格中照片的索引并将其添加 1,以便它与列表中相应信息框的索引与所有教授相匹配。显然变量 itemIndex 在 nth-child 方法中没有被识别为参数。

另一个想法是使用 for 循环:

$("#proftable td").click(function() {
    for ( var i = 0; i < 22; i++ ) {
        if ( i == $(this).index() ) {
            $("#kartenliste .visitenkarte:nth-child(i + 1)").show(); 
        };
    };
});

我们系有 22 位教授,因此 i 的最终值。但是,这也不起作用...

有人有更好的主意吗?我真的很感激。

提前谢谢你!

【问题讨论】:

  • $("#kartenliste .visitenkarte:nth-child(" + itemIndex + ")").show(); //?
  • 我也想知道引号之间是否无法识别变量...我试过了,但仍然没有结果。还是感谢您的回复!
  • 又是我 :) 您实际上是对的:索引值需要添加到引号之外。我更仔细地阅读了 index() 的文档,终于明白了它是如何工作的。这是(现在可以使用的)代码:var itemIndex = $("td").index(this);$("#kartenliste .visitenkarte:nth-child(" + itemIndex + 1 + ")").show();
  • 很高兴解决了。感谢您的更新!

标签: jquery html for-loop indexing


【解决方案1】:

你可以使用$("#kartenliste .visitenkarte").eq(itemIndex).show()

【讨论】:

  • 谢谢你,你的想法也行。我只需要记住,nth-child 从 1 开始,eq 在 0 :)
  • @TeodorChiaburu 我正在为一些宝贵的声望点投票:-D
  • 我还不能投票,我刚刚订阅了该网站。我也需要一些积分,以便能够通过投票提供反馈:-)
【解决方案2】:

我认为最好的解决方案是在你的 td 中添加一个自己的 attr,然后用相同的 id 显示这个 div

<td own-attr="visprof1">Prof John</td>

<div id = "kartenliste">

<div class="w3-card-4 visitenkarte hidden" id="visprof1">
    *info about the first professor*
</div>

</div>

然后在jQ中

$('td').click(function(){
   var showById=$(this).attr('own-attr');
   $('.visitenkarte#'+showById).show();
});

【讨论】:

  • 谢谢!聪明的主意,我看到你在那里做了什么。你的代码也有效。所以现在我有三个选项可供选择:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 2021-05-05
  • 1970-01-01
相关资源
最近更新 更多