javascript - 从 bootstrap 弹出窗口打开隐藏的 div

标签 javascript jquery twitter-bootstrap

我在页面上有一个隐藏的 div,需要通过点击功能打开。

可点击的链接位于 Bootstrap 弹出窗口内,因此如何通过单击弹出窗口内容链接来打开页面 div。

这里是Fiddle

$( "#open" ).click(function() {
      $('.open-this').slideToggle("slow");
    });

最佳答案

而不是这段代码:

$( "#open" ).click(function() {
      $('.open-this').slideToggle("slow");
    });

试试这个

$("body").on("click","#open",function(e) {
    e.preventDefault();
      $('.open-this').slideToggle("slow");
    });

查看更新后的 fiddle http://jsfiddle.net/bfkLM/15/

您的代码存在的问题是,当您的事件处理程序尝试将 click 事件附加到它时,该链接是从您的代码生成的,并且未在 dom 中呈现。

所以解决方案是使用委托(delegate)事件: 来自官方; jquery 网站

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

这就是为什么我的新代码可以工作,因为它将事件处理程序附加到 body 标记,并检查点击事件是否来 self 的目标元素 (open),当发生这种情况时,它将启动我的代码并显示弹出窗口

还有一件事,使用 e.preventDefault(); 是为了防止页面导航到 anchor 的 href 属性。

关于javascript - 从 bootstrap 弹出窗口打开隐藏的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19158364/

相关文章:

javascript - 将 Canvas 定位在重叠 Canvas 下方

javascript - 我如何从多个链接调用相同的 fancybox javascript?

javascript - jquery ajax 没有将数据传递给 php?

html - 为什么我不能隐藏我的 br 标签?

css - 没有内容只是背景,为什么有滚动条?

javascript - NodeJS循环模块应用程序结构

javascript - jQuery:在选择更改时隐藏/显示多个 div

javascript - 如何在 jQuery 中编辑 css 规则?

html - 试图将扩展导航栏从右侧移动到左侧

javascript - 更改下拉列表中一行的颜色