对象元素中的图片javascript

时间:2018-01-14 14:57:30

标签: javascript

我必须随机引用,为了更好的设计,我想把那个说出来的男人的形象。 例如: 我的尝试"

 var quote = [
      '\"Don\'t cry because it\'s over, smile because it happened.\" ―  Dr. Seuss', '\"Be yourself; everyone else is already taken.\" ― Oscar Wilde',
  '\"A room without books is like a body without a soul.\" ― Marcus Tullius Cicero',
  '\"You only live once, but if you do it right, once is enough.\" ― Mae West',
  '\"Be the change that you wish to see in the world.\" ― Mahatma Gandhi']

我需要Seuss的图片,所以我该怎么办呢?我有一些想法,但我不知道如何实现它们。我需要帮助!我的网站会做它所需的一切。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以通过多维阵列实现您想要的效果。

var quote = [
  ['\"Don\'t cry because it\'s over, smile because it happened.\" ―  Dr. Seuss', 'http://example.com/randomimage.jpg'], 
  ['\"Be yourself; everyone else is already taken.\" ― Oscar Wilde', 'http://example.com/randomimage.jpg'],
  ['\"A room without books is like a body without a soul.\" ― Marcus Tullius Cicero', 'http://example.com/randomimage.jpg'],
  ['\"You only live once, but if you do it right, once is enough.\" ― Mae West', 'http://example.com/randomimage.jpg'],
  ['\"Be the change that you wish to see in the world.\" ― Mahatma Gandhi', 'http://example.com/randomimage.jpg']
];

答案 1 :(得分:0)

假设您希望图片旁边的图像(不是内联)。您可以在该引用变量中使用img src,例如:

var quote = {
    'author_img' : '/imgs/author/Seuss',
    'quote' : '...'
};

您可以像这样访问它:

quote.author_img 
quote.quote

超级基本代码段:

var quote = {
    'author_img' : 'https://upload.wikimedia.org/wikipedia/commons/d/d1/Portrait_Gandhi.jpg',
    'quote' : 'Happiness is when what you think, what you say, and what you do are in harmony.'
};

$( document ).ready(function() {
    $('button').click(function(){
        $('#quote img').attr('src', quote.author_img);
        $('#quote p').text(quote.quote);
    });
});
#quote img{
  width: 100px;
  float:left;
  margin-right: 25px;
}

.clearfix:after{
  float:none;
  display:table;
  content:"";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quote" class="clearfix">
<img src="https://i.stack.imgur.com/MdvUu.png?s=128&g=1" alt="" title=""/>
<p>Default message</p>
</div>

<button>CLICK ME TO CHANGE QUOTE</button>

答案 2 :(得分:0)

由于你没有包括你当前如何在该数组中显示引号,我只是假设你在问......

  

如何为数组中的每个引号存储图像?

这可以通过使数组中的每个项目成为对象来完成,如下所示:

var quotes = [
  {
    text: '\"Don\'t cry because it\'s over, smile because it happened.\" ―  Dr. Seuss',
    picture: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Ted_Geisel_NYWTS_2_sepia.jpg'
  }
]

我还建议将作者姓名放入另一个属性中:

var quotes = [
  {
    author: 'Dr. Seuss',
    text: "Don't cry because it's over, smile because it happened.",
    picture: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Ted_Geisel_NYWTS_2_sepia.jpg'
  }
]

要显示引号,您可以循环其他引号并使用author获取textpicturequote.author,...