如何使用下拉列表更改图片? [英] how to change picture using drop down list?

查看:105
本文介绍了如何使用下拉列表更改图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个下拉列表,每次点击其中的内容时,会出现不同的图片。但是我不想使用属性值,因为我想使用这些值进行其他用途。

I want to use a drop down list, every time i click the content in it, different pictures will show up. But i don't want to use the property 'value', because i want to use the values for other use.

示例:

<select name='test'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>

如何实现?

谢谢。

编辑:

与尖尖的建议,它的作品。

with pointy's suggestion, it works.

<select name="dpt" onChange="picture.src=this.options[this.selectedIndex].getAttribute('data-whichPicture');" >
<option value="1839" data-whichPicture='./imgs/t1.jpg' >01</option>
<option value="1661" data-whichPicture='./imgs/t2.png' >02</option>
</select>
</select>
<img src='' id='picture' />

编辑:

有一个问题,那就是如果我刷新页面,默认的图片将显示,但下拉列表中的选择将保留。如何修复?

There is a problem, that is if i refresh the page, the default the picture will display but the selection in the drop down list will stay. How to fix that?

推荐答案

您可以使用每个选项的类来保存显示的图像的一些指示符。如果你像现在所有的美丽人物一样编写HTML5,可以使用data属性:

You could use the "class" of each option to hold some indicator of what image to show. If you're writing in HTML5 like all of the Beautiful People nowadays, you can use a "data" attribute:

<option value='1' data-whichPicture='http://whatever.com/picture_017.jpg'>1</option>

您实际上可以在标签上粘贴任何您想要的属性,但会将页面非有效状态。 HTML5属性尚未验证(我不认为,我上次尝试的HTML5验证程序非常狡猾),但是W3C承诺将会有一天。

You can in fact stick any attribute you want on your tags, but it'll leave the page in a non-valid state. The HTML5 attributes aren't validated yet (I don't think; the HTML5 validator I last tried was pretty dodgy), but the W3C promises that they will be someday.

编辑—还有 - 您的问题提到您想要在< select> 中的某人点击时更改图片。事实上,您可以从每个< option> 获取点击事件,但您也应该注意更改事件。用户可以选择您的< select> ,并使用向上和向下箭头键更改选择。直到用户从< select> 中选择标签或点击别的地方,才会得到更改事件。 (可能有可能获得按键事件;我没有尝试过,但我可能会...)

edit — also - your question mentions that you want to change pictures when somebody "clicks" on the <select>. You can in fact get "click" events from each <option>, but you should probably also watch for "change" events. Users can tab into your <select> and use up- and down-arrow keys to change selection. You won't get the "change" event until the user tabs out of the <select> or clicks somewhere else. (It might be possible to get "keypress" events; I haven't tried that but I just might ...)

编辑&mdash ;要获取属性(如果使用data-技巧),您必须在元素上使用getAttribute方法:

edit — To get the attributes (if you use the "data-" trick), you have to use the "getAttribute" method on the elements:

var whichPicture = sel.options[sel.selectedIndex].getAttribute('data-whichPicture');

这篇关于如何使用下拉列表更改图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆