jQuery 更改图像与选择不工作

标签 jquery html css

我正在尝试对下拉菜单进行简单的图像更改,但由于某种原因我无法使其正常工作,任何人都可以告诉我我缺少什么吗?

Jsfiddle here有代码。

谢谢大家!

$("#display_avatar").change(function(){
    $("img[name=preview]").attr("src", $("option").attr("imagePath"));
    event.preventDefault();
});

<img src="http://placehold.it/100/0000FF/000000" name="preview" /><br /><br />

<select class="form-control" name="display_avatar" id="display_avatar">
    <option value="1" imagePath="http://placehold.it/100/cccccc/000000">First</option>
    <option value="2"imagePath="http://placehold.it/100/ghghgh/000000">Second</option>
    <option value="3"imagePath="http://placehold.it/100/5fgrty/000000">Third</option>
    <option value="4"imagePath="http://placehold.it/100/ff0000/000000">Fourth</option>
</select>

最佳答案

这只会从第一个选项中获取值:

$("option").attr("imagePath")

试试这个:

this.selectedOptions[0].getAttribute("imagePath")

更新 fiddle :http://jsfiddle.net/979vbv0j/2/

关于jQuery 更改图像与选择不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27593966/

相关文章:

jquery 防止拖动选择文本

javascript - 我需要设置显示: block on div then find an anchor within that div

html - 简单的 HTML/CSS 问题 - 高度和屏幕分辨率

javascript - 使用 javascript 突出显示代码示例中的语法。

javascript - CSS 过渡淡入原始文本颜色

css - 重构重复的 sass 以根据直接父类进行修改

javascript - 在内容可编辑的 div 上强制尺寸?

jquery - 如何使用jquery将一个文本框中输入的值反射(reflect)到另一个文本框中

javascript - 使用 jQuery 单击背景容器时隐藏元素

HTML/CSS - 内联 block 显示和绝对定位