【问题标题】:How can I show an image based on the selection in a dropdown?如何根据下拉菜单中的选择显示图像?
【发布时间】:2020-09-11 18:42:46
【问题描述】:

我希望我的网站发布图像作为仅包含文本的选择选项值的结果。例如:

<select name="facebook" id="facebook">
  <option value="Facebook"> Facebook </option>
</select>
<button type="submit" name="submit"> Submit </button>

上面的选择标签显示了一个值为“Facebook”的选项。当您选择此选项并单击提交时,我希望网站根据所选的选项值发布 Facebook 徽标的图像(从文件夹或图像 URL 中检索)。

此外,我将值插入到表 table_1 中,然后从表中选择值以在网站上回显它们。这是检索值并将它们作为文本发布的想法,但正如我所说,我想检索信息但发布图像

【问题讨论】:

  • 你想把它发布到哪里?
  • 嗨,您在后端使用的是哪种语言?
  • @Argee,我没有指定任何要发布结果的文件。但主要思想是检索我已经存储在文件夹中的图像,并发布指定的图像在索引页面上选择选项。不知道你是不是这个意思,还是?
  • 嗨@qdequippe,我不完全理解我在后端使用的语言是什么意思。但是,我知道和使用的唯一编程语言是 PHP、HTML 和 CSS。

标签: javascript html jquery


【解决方案1】:

在您的按钮旁边添加一个img 元素(src=""),然后使用 jQuery 使用.attr() 对其进行修改。要查找从下拉列表中选择的选项 (#select),请使用 :selected 选择器并获取它的值 (val())。

$(document).on('click', '#submit', function() {
  $('#logo').attr('src', '//via.placeholder.com/150?text=' + $('#select').find(':selected').val()); // replace this with whatever you want
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="logoSelect" id="select">
  <option value="facebook"> Facebook </option>
  <option value="twitter"> Twitter </option>
  <option value="google"> Google </option>
  <option value="instagram"> Instagram </option>
</select>
<button id="submit" type="submit" name="submit"> Submit </button>
<br/><br/>
<img id="logo" src=""></img>

您也可以通过使用纯 JavaScript 和 onclick.selectIndex 方法来实现这一点:

const logoImgElem = document.getElementById('logo');
const selectElem = document.getElementById('select');
document.getElementById('submit').onclick = function() {
  logoImgElem.src = '//via.placeholder.com/150?text=' + select.options[select.selectedIndex].text;
};
<select name="logoSelect" id="select">
  <option value="facebook"> Facebook </option>
  <option value="twitter"> Twitter </option>
  <option value="google"> Google </option>
  <option value="instagram"> Instagram </option>
</select>
<button id="submit" type="submit" name="submit"> Submit </button>
<br/><br/>
<img id="logo" src=""></img>

【讨论】:

  • 感谢@double-beep 的回答。不过我有一个问题,我尝试输入您在&lt;script src=""&gt; 中放置的链接,但我发现了很多未知语言。请问这对您在答案中发布的示例有什么影响?这是我需要的东西吗?
  • @TobiasRingsø 这会插入一个名为 jQuery 的 JavaScript 库(您可以从 here 开始)。此示例使用 jQuery(您可以通过使用 $() 来判断),因此需要这一行。
  • @TobiasRingsø 我添加了一个不需要 jQuery 的示例。
猜你喜欢
  • 2010-11-21
  • 2017-10-06
  • 2017-05-18
  • 2022-12-06
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
相关资源
最近更新 更多