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

标签 javascript jquery html events dom

我对整个 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 传递给我的函数?

最佳答案

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

还要尝试避免在标签中使用内联脚本事件处理程序。最好将这些事件挂接到文档中。

NB 下面的代码假设调用处理程序的元素(链接)位于表内部,因此可以使用最接近的元素遍历到它。情况可能并非如此,您可能需要根据您的标记使用其他遍历选项之一。

$(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");
   }
}

关于javascript - 是否有更简单的方法来引用事件的源元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1234585/

相关文章:

javascript - Google 脚本 - 在 html 上显示根据 google.gs 函数计算的结果

javascript - 需要在将内容滚动到底部时从水平滚动菜单列表显示事件菜单

javascript - 我可以继续使用之前的阻止链接吗?

jquery 与 $(this) 相反

php - 从 php 中的数据中删除损坏的 html 标签

javascript - 诺基亚 map (v2.2) : mousedown/mouseup issue

javascript - $资源;如何封装API方法

javascript - jQuery for 循环与数组(计数数组)

javascript - 如果加载元素,则 JS 执行函数 - 没有 jQuery

javascript - 使用 for 循环将 onclick 方法附加到多个 Canvas