twitter-bootstrap 如何使用 ajax 使 Twitter Bootstrap Collapse 在动态加载的 html 上工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13910596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make Twitter Bootstrap Collapse work on dynamically loaded html using ajax
提问by Mr Spark
I am loading html using ajaxcall, this html has Bootstrap Collapse. The issue is Collapse is not working, if you click it will expand but it won't collapse again.
我正在使用ajax调用加载 html ,这个 html 有Bootstrap Collapse。问题是折叠不起作用,如果您单击它会展开但不会再次折叠。
To check if I am doing something wrong, I put the same code on a static page (not loaded using ajax) and it works fine. So its seems issue only with dynamically loaded html.
为了检查我是否做错了什么,我将相同的代码放在静态页面上(未使用 ajax 加载)并且它工作正常。所以它似乎只有动态加载的 html 才有问题。
I tried manually enabling Collapse using
我尝试使用手动启用折叠
$(".collapse").collapse()
but still same issue.
但仍然是同样的问题。
I guess I need to use jquery's live() / on()methods, because the html is dynamic, but not sure how do I do that for calling $(".collapse").collapse()because I think it only works on events or is it something else that I need to do ?
我想我需要使用 jquery 的live() / on()方法,因为 html 是动态的,但不确定我该如何调用,$(".collapse").collapse()因为我认为它只适用于事件还是我需要做的其他事情?
采纳答案by bipen
i would suggest you to call
我建议你打电话
$(".collapse").collapse()
inside the ajax's success function after the dynamic html is appended.
附加动态 html 后在 ajax 的成功函数中。
回答by NamPNQ
My solve is:
我的解决方法是:
$('.collapse').on('show', function () {
var $this = $(this);
if($this.attr('data-href'))
{
$this.html($.getJSON($this.attr('data-href'),function(data){
$this.html(data.html);
$this.removeAttr('style');
}));
}
})
回答by barek2k2
Just execute this on ajax success event.
只需在 ajax 成功事件上执行此操作。
$('[data-toggle="collapse"]').click(function(e){
e.preventDefault();
var target_element= $(this).attr("href");
$(target_element).collapse('toggle');
return false;
});

