我对整个 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/