简体   繁体   English

JS:输出不一致

[英]JS: output inconsistencies

This code gets the user input and substitute it to "selected", Example 此代码获取用户输入并将其替换为“ selected”,示例

1st Input 第一输入
User Input: 用户输入:

Apple

Process(what happens inside): 处理(内部发生什么):

"img2/" + Apple + ".jpg";

Output: 输出:

Apple.jpg (image)

The problem is once the user inputs a query that doesn't have the corresponding image the code, outputs the previous one 问题是,一旦用户输入的查询没有相应的图像代码,则输出前一个

2nd Input User Input: 第二输入用户输入:

Orange

Process(what happens inside): 处理(内部发生什么):

"img2/" + Apple + ".jpg";

Output: 输出:

Apple.jpg (image) //wrong incorrect

 var q = document.getElementById("code");


if (q.selectedIndex > 0) { 

var selected = q.options[q.selectedIndex].value;
var src = "img2/" + selected + ".jpg";
var img = document.getElementById("placeholderImg");
img.src = src;
img.style.display = "inline";

}

<select name="code" id="code" size="" disabled="true" hidden="true">
<option value="Apple">Apple</option>
<option value="Atis">Atis</option>
//so on and so forth

how can I fix this? 我怎样才能解决这个问题? any suggestion opinion is highly appreciated 任何建议意见都受到高度赞赏

Your mistake lays within the line 你的错误就在行内

if (q.selectedIndex > 0)

The selectedIndex property is 0 when the first row is selected (in your case "Apple"). selectedIndex第一行(在您的情况下为“ Apple”)时, selectedIndex属性为0 Therefor this if statement will only work if something else than "Apple" is selected. 因此,仅当选择了“ Apple”以外的内容时,此if语句才起作用。
The selectedIndex property is -1 when nothing is selected, not 0 ! 如果什么也没有选择,则selectedIndex属性为-1 ,而不是0

You should replace it with the following statement: 您应该用以下语句替换它:

if (q.selectedIndex > -1)

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

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