简体   繁体   English

更改为引导表后,jQuery在“单击”时未触发

[英]jQuery on 'click' not triggering after change to a bootstrap table

situation 情况

I am using bootstrap to render a table based on values in an array of objects. 我正在使用引导程序根据对象数组中的值呈现表。 I have a select which has a jQuery on ('change') method attached so that when an item from the list is selected, a new table is rendered based on the selected value. 我有一个选择附加了jQuery on('change')方法,以便从列表中选择一个项目时,将根据所选值呈现一个新表。

the table uses bootstrap collapse to show/hide rows from the table when the top row is clicked. 当单击第一行时,该表使用引导折叠来显示/隐藏表中的行。 the last item in the row has a glyphicon arrow which shows the row can be folded/unfolded as the picture below shows 该行的最后一项有一个glyphicon箭头,表示该行可以折叠/展开,如下图所示

collapse with glyphicon 用雕ly塌陷

I am using the below jQuery to toggle the icon 我正在使用下面的jQuery来切换图标

$('#tog').on('click', function() {
  console.log("tog clicked");
  $(this).find('span').toggleClass('glyphicon-arrow-up glyphicon-arrow-down');
});

so far I have this all working as shown with this fiddle http://jsfiddle.net/vgfb74u0/ 到目前为止,我已经按照提琴http://jsfiddle.net/vgfb74u0/

Problem 问题

the issue I am facing is that when a new table is rendered based on the selected item the jQuery that changes the glyphic does not trigger so when the table unfolds the icon remains the same. 我面临的问题是,当基于所选项目呈现新表时,更改字形的jQuery不会触发,因此当表展开时,图标保持不变。

I have put in some console.log at the start of the method and I never see it firing. 我在该方法的开头放置了一些console.log,但从未看到它触发。 so to my newbie eyes the click event is never triggered. 因此,对我的新手来说,点击事件从未触发过。

I'm surprised that i've managed to get this far and at a loss to what the issue might be so any help, pointers or advise is most welcome! 令我感到惊讶的是,我已经设法做到了这一点,对问题可能是茫然不知所措,因此欢迎任何帮助,指导或建议!

You need to manually bind events to any dynamically created element, or let jQuery do that for you. 您需要手动将事件绑定到任何动态创建的元素,或者让jQuery为您完成。

Changing 改变中

$('#tog').on('click', function() {});

To

$('html').on('click', '#tog', function() {});

Will tell JavaScript to delegate the event to any #tog that's created inside the <html> element. 将告诉JavaScript将事件委托给<html>元素内创建的任何#tog

The problem is the event handler is lost when the table is re-rendered. 问题在于重新渲染表时事件处理程序丢失了。 The fix is to attach the handler in a different way: $('.table').on('click', '#tog', function() {...} 解决方法是以其他方式附加处理程序: $('.table').on('click', '#tog', function() {...}

See the updated jsfiddle 查看更新的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM