twitter-bootstrap 如何使用 bootstrap popover 来显示同级元素或子元素的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14265616/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 16:05:15  来源:igfitidea点击:

How do I use the bootstrap popover to display the content of a sibling or child element?

twitter-bootstrappopover

提问by Justin Helgerson

I am trying to get the bootstrap popover to display contextual content based on what element is being setup with popover.

我试图让 bootstrap popover 显示基于使用 popover 设置的元素的上下文内容。

Here's some example markup:

下面是一些示例标记:

<div class="user">
    <img src="foo.jpg" />
</div>
<div class="userInfo">
    <p>He likes pie!</p>
</div>

<div class="user">
    <img src="bar.jpg" />
</div>
<div class="userInfo">
    <p>He likes cake!</p>
</div>

The script to setup the popover:

设置弹出框的脚本:

$('.user').popover({
    trigger: 'hover',
    placement: 'top',
    html: true,
    content: //What goes here?  I want to display the contents of the userInfo class
});

The expected result when I hover over the userclass would be to show a popover displaying the content contained in the sibling or child userInfoclass.

当我将鼠标悬停在user类上时,预期的结果是显示一个弹出窗口,其中显示了兄弟userInfo类或子类中包含的内容。

My markup can be flexible; I can move the userInfoclass to be a child, sibling, parent, etc.

我的标记可以很灵活;我可以将userInfo班级转变为孩子、兄弟姐妹、父母等。

回答by hajpoj

Yeah I would put the .userInfoinside of .user, then iterate over $('.user')and set the content for each .userseparately (in your example you are setting the same content for all the popovers.

是啊,我会把.userInfo里面.user了,然后循环$('.user'),并为每个内容.user分开(在你的例子中,你正在为所有popovers相同的内容。

Example:

例子:

<div class="user">
  user 1
  <div class="userInfo">
    <p>He likes pie!</p>
  </div>
</div>

<div class="user">
  user 2
  <div class="userInfo">
    <p>He likes cake!</p>
  </div>
</div>

Javascript:

Javascript:

$('.user').each(function() {
  var $this = $(this);
  $this.popover({
    trigger: 'hover',
    placement: 'right',
    html: true,
    content: $this.find('.userInfo').html()  
  });
});

Here is a working jsfiddle (added some extra css): http://jsfiddle.net/hajpoj/CTyyk/5/

这是一个有效的 jsfiddle(添加了一些额外的 css):http: //jsfiddle.net/hajpoj/CTyyk/5/

回答by Cam

You could leave his original markup and use this:

你可以留下他的原始标记并使用这个:

$('.user').each(function() {
  var $this = $(this);
  $this.popover({
    trigger: 'hover',
    placement: 'right',
    html: true,
    content: $this.next().html()  
  });
});