简体   繁体   English

在JavaScript中调用组合框值

[英]Call combo box value in JavaScript

How can I use the selected combo box item as a variable for the use of javascript image calling? 如何将所选组合框项目用作使用javascript图像调用的变量?

HTML HTML

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

JavaScript 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'"/>');

Now, obviously this doesn't work. 现在,显然这是行不通的。 How can I make it work? 我该如何运作? Its really just the document.write line that needs to be fixed. 它实际上只是需要修复的document.write行。

You should be using document.write() to insert content on the fly while document is being loaded. 您应该在加载文档时使用document.write()快速插入内容。

According to MDN's doc : 根据MDN的文档

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open() call 在不调用document.open()情况下写入已加载的document.open()将自动执行document.open()调用

And from document.open() : document.open()

If a document exists in the target, this method clears it 如果目标中存在文档,则此方法将其清除

So, Using document.write() after the document is loaded will overwrite ( or clear ) your document. 因此,在加载文档后使用document.write()会覆盖( 或清除 )您的文档。 For such reasons, using document.write() is considered a bad practice . 由于这些原因, 使用document.write()被认为是不好的做法

Using 运用

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

instead will fix the issue. 而是可以解决此问题。

See also What are alternatives to document.write? 另请参见什么是document.write的替代方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM