使用 jQuery 添加可点击的 table 标题

Adding a clickable table caption with jQuery

我想向带有 jQuery 的 table 添加可点击的标题。我这样添加:

$("table.table-legend").prepend('<caption class="edit-select"><a href="javascript:;">Select All - None</a></caption>');

这有效,我确实得到了一个可点击的标题,但我不知道如何定义被调用的函数。

我试过:

$('table caption a').on('click', function () {

$('.edit-select a').on('click', function () { 

还有其他一些方法,但无论如何,我的函数没有被调用。这样做的正确方法是什么?

$(document).on('click', '.edit-select a', function() {
    // do stuff
});

jQuery 仅在页面运行时识别页面中的元素,因此 jQuery 无法识别添加到 DOM 的新元素。为了对抗这种情况,请使用 event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

请记住,在页面加载期间动态添加到 DOM 的元素可以在不依赖冒泡和委托的情况下进行绑定,只要在包含元素后将事件绑定到它们即可。考虑以下 example -

var newKid = '<div class="kid">Jan</div>';
$('.parent').append(newKid);

$('.kid').click(function() {
    var kidName = $(this).html();
    var message = kidName + ' got clicked<br />';
    $('.whoGotClicked').append(message);
});

var newKid = '<div class="kid">Cindy</div>';
$('.parent').append(newKid);

您认为此处的 'got clicked' 列表中会添加哪些人? Marsha 包含在原始标记中,Jan 作为脚本 运行 添加到 DOM,但在点击事件绑定到孩子 class 之前。绑定发生后,Cindy 被添加到 DOM。 Marsha 和 Jan 都由点击事件处理,而 Cindy 则被冷落。使用事件委托

$(document).on('click', '.kid', function() {...

将确保所有孩子现在和将来都能得到 handled

$("table.table-legend").prepend('<caption class="edit-select"><a> href="javascript:;">Select All - None</a></caption>');

这是实际代码还是您只是复制了其中的一部分?

您在锚标记开头后的文本中有错字:href 选择器看起来不错。

这里是the snippet

编辑:

javascript 调用的顺序很重要。在 DOM

中插入字幕后,您需要分配点击事件