如何定位选项的数据属性?

时间:2015-09-18 23:38:57

标签: javascript jquery html5

我尝试根据用户选择的dropdown/select选项进行图片更改。但是,我需要使用data属性而不是更简单的option值来执行此操作,因为我需要将其用于其他内容。我似乎无法弄清楚我做错了什么。我附加的代码并未定位data-image属性。我认为我做错了什么?

示例代码:

<html>
<div>
    *Flavor 1:
</div>
<div>
    <select class="custom-cupcake-flavor" name="custom-cupcake-flavor">
        <option data-image="noimage.jpg" value="">-- Please Choose an Option --</option>
        <option data-image="Chocolate-Covered-Strawberry.jpg" value="Chocolate Swirl">Chocolate Swirl</option>
        <option data-image="strawberryLemonade.jpg" value="Extreme Lemon">Extreme Lemon</option>
        <option data-image="Cookie-Dough-Delight.jpg" value="Vanilla Blast">Vanilla Blast</option>
    </select>
</div>


<br>

<div class="col-md-6">
    <img id="uploadedImage" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=400%C3%97400&w=400&h=400">
    <br>

</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

<div style="clear:both;"></div>
<script type='text/javascript'>
    $(document).ready(function() {
        var flavor;
        var image_name;

        $(".custom-cupcake-flavor").on('change', function() {
            flavor = $(this).data("image");
            image_name = ("/images/" + flavor);

            $('#uploadedImage').fadeOut(200, function() {
                $('#uploadedImage').attr('src', image_name).bind('onreadystatechange load', function() {
                    if (this.complete) $(this).fadeIn(400);
                });
            });
        });

    });
    <!-- Hides Product Image when "No image" option is selected.-->
    $(document).ready(function() {
        $('.custom-cupcake-flavor').on('change', function() {
            if (this.val() !== "") {
                $("#uploadedImage").hide();
            } else {
                $("#uploadedImage").show();
            }
        });
    });
</script>

</html>

1 个答案:

答案 0 :(得分:3)

您可以使用:selected selector在下拉列表中获取所选内容:

$('.custom-cupcake-flavor').on('change', function() {
    var $option = $(this).find(':selected');
    var imageUrl = $option.data('image');

    // You might want to do something with imageUrl here:
    $('#uploadImage').attr('src', imageUrl);
});
// If you want to run the above on initial load you can trigger the change event:
// $('.custom-cupcake-flavor').trigger('change');