【问题标题】:Jquery Cycle through table rows [closed]Jquery循环遍历表行[关闭]
【发布时间】:2012-02-23 15:34:04
【问题描述】:

我需要设置 jQuery 来循环遍历表格行。该表应始终只显示一行。当我点击链接时,应该会显示上一行或下一行。

基本的HTML结构是:

<div>
<a href="">Next</a>
<table>
  <tr><td>text1</td></tr>
  <tr><td>text2</td></tr>
  <tr><td>text3</td></tr>
  <tr><td>text4</td></tr>
</table>
<a href="">Previous</a>
</div>

任何帮助将不胜感激。

【问题讨论】:

  • 有什么问题?你试过什么?你遇到了什么麻烦?
  • 你所说的“在行中循环”是什么意思?

标签: jquery html-table rows cycle


【解决方案1】:

不清楚您所说的“循环遍历行”是什么意思,但有一些构建块:

  1. 您可以使用 CSS 选择器(几乎所有 CSS3 plus some)在 DOM 中查找元素。例如,这会找到所有 a 元素:

    var links = $('a');
    
  2. 您可以通过on(或者如果您使用的是旧版 jQuery,bind)将事件挂钩。

  3. 在处理事件时,您可以使用preventDefault 来防止事件的默认操作(例如,防止点击链接跟随链接)和/或stopPropagation(防止事件冒泡 DOM),或者通过在事件处理程序中返回 false 来实现两者。

  4. jQuery 是基于集合的,因此 jQuery 实例可以是多个元素的包装器,例如var rows = $('tr');.

  5. 您可以索引一个 jQuery 实例来访问匹配集中该点的原始 DOM 元素,例如rows[2] 是集合中的第三行。

例如,如果您将 "next" 类添加到“下一个”链接:

<a href="" class="next">Next</a>

...您可以使用选择器找到它并挂钩click 事件:

$('a.next').on('click', function(event) {
    // This function is called when the link is clicked
    // ...

    // Prevent the browser from actually following the link
    // and stop the event bubbling
    return false;
});

因此,您可以保留“当前”行的索引,索引到包装这些行的 jQuery 实例,并在点击时对其进行处理。

值得花一两个小时阅读API docs。从字面上看,这需要很长时间,并且您会获得丰厚的回报。

【讨论】:

    【解决方案2】:

    首先,为您的元素提供 id:

    <a id="next" href="">Next</a>
    <table id="myTable">
        <tr><td>text1</td></tr>
        <tr><td>text2</td></tr>
        <tr><td>text3</td></tr>
        <tr><td>text4</td></tr>
    </table>
    <a id="prev" href="">Previous</a>
    

    然后,隐藏除第一个之外的所有元素:

    $("#myTable tr").hide().eq(0).show();
    

    最后,让“下一个”和“上一个”按钮切换相邻兄弟的可见性(如果存在):

    $("#next").click(function(e) {
        e.preventDefault();
        $("#myTable tr:visible").next().show().prev().hide(); // Will do nothing if the visible element is the last one
    });
    
    $("#prev").click(function(e) {
        e.preventDefault();
        $("#myTable tr:visible").prev().show().next().hide(); // Will do nothing if the visible element is the first one
    });
    

    【讨论】:

      猜你喜欢
      • 2011-03-09
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 2017-05-21
      • 2023-03-09
      相关资源
      最近更新 更多