代码之家  ›  专栏  ›  技术社区  ›  stsquad

是否有更简单的方法来引用事件的源元素?

  •  2
  • stsquad  · 技术社区  · 15 年前

    我对整个javascript和jquery编码都是新手,但我目前正在做的是我的HTML:

    <a id="tog_table0" 
      href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a>
    

    然后我有一些稍微冗长的代码来调整元素:

    function toggle_table(button_id, table_id) {
             // Find the elements we need
             var table = $(table_id);
             var button = $(button_id);
             // Toggle the table
             table.slideToggle("slow", function () {
             if ($(this).is(":hidden"))
         {
        button.text("show");
         } else {
           button.text("hide");
         }
        });
    }
    

    我主要想知道是否有一种更整洁的方法来引用源元素,而不是必须将两个ID传递给我的函数?

    3 回复  |  直到 15 年前
        1
  •  2
  •   redsquare    15 年前

    在事件中使用“this”。通常在jquery中,这指的是调用处理程序的元素。

    同时尝试避免在标记中使用内联脚本事件处理程序。最好将这些事件连接到文档就绪中。

    下面的代码假定调用处理程序(链接)的元素在表中,因此可以使用closest遍历它。可能情况并非如此,您可能需要根据标记使用其他遍历选项之一。

    $(function(){ 
       $('#tog_table0').click( toggle_table )
    });
    
    function toggle_table() {
       //this refers to the element clicked
       var $el = $(this);
       // get the table - assuming the element is inside the table
       var $table = $el.closest('table');
       // Toggle the table
       $table.slideToggle("slow", function () {
           $el.is(":hidden") ? $el.text("show") : $el.text("hide");
       }
    }
    
        2
  •  1
  •   jammus    15 年前

    您可以这样做:

    <a href="" name="#hideable_table0" class="tableHider">show</a>
    

    并将您的javascript更改为:

    $('a.tableHider').click(function() {
        var table = $(this.name); // this refers to the link which was clicked
        var button = $(this);
    
        table.slideToggle("slow", function() {
            if ($(this).is(':hidden')) { // this refers to the element being animated
                button.html('show');
            }
            else {
                button.html('hide');
            }
        });
    
        return false;
    });
    

    编辑:将脚本更改为使用name属性,并向单击处理程序添加了返回false。

        3
  •  0
  •   jyoseph    15 年前

    我确信这并不能回答您的问题,但是有一个漂亮的插件可以扩展表行,可能有助于检查它:

    http://www.jankoatwarpspeed.com/post/2009/07/20/Expand-table-rows-with-jQuery-jExpand-plugin.aspx