javascript - 在 JavaScript 中调用组合框值

标签 javascript html

如何使用选定的组合框项目作为变量来使用 javascript 图像调用?

HTML

<select id="fileType">
 <option value=".jpg">.JPG</option>
 <option value=".png">.PNG</option>
 <option value=".gif">.GIF</option>
</select>

JavaScript

var selectedComb = document.getElementById("fileType");
var selectedFileType = selectedComb.options[selectedComb.selectedIndex];
var selectedType = selectedFileType.value;

document.write('<img src="example.com/images/pic + 'selectedType'"/>');

现在,显然这不起作用。我怎样才能让它发挥作用?实际上只是需要修复 document.write 行。

最佳答案

您应该使用document.write()在加载文档时动态插入内容。

根据MDN's doc :

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open() call

来自 document.open() :

If a document exists in the target, this method clears it

所以,使用 document.write()加载文档后将覆盖(或清除)您的文档。出于这样的原因,using document.write() is considered a bad practice .

使用

document.body.innerHTML+= '<img src="example.com/images/pic' +selectedType+ '"/>';

相反会解决问题。

另请参阅What are alternatives to document.write?

关于javascript - 在 JavaScript 中调用组合框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085668/

相关文章:

jQuery 选择一个 block 并使用列表中 block 之一的 bg 颜色更改它的 bg 颜色

javascript - 如何在选项元素内创建中断

javascript - 为什么我的复选框上的 <required> 属性不工作,尽管已经设置了一些 JS 代码使其成为一个要求?

javascript - Backbone.js View 在其创建期间的生命周期

javascript - 使用 Redux 在 React 组件中执行后台任务

javascript - 焦点不适用于文本字段

javascript - 如何在javascript中检测窗口的全高

javascript - d3 使 Y 轴位置固定,即使滚动条 x

javascript - 如何让禁用的按钮在单击时执行某些操作? (JS)

javascript - 输入数字时如何在数字输入字段中添加破折号?