使用数据属性更改元素的背景图像。

时间:2015-02-25 23:05:34

标签: jquery html

我尝试使用jQuery函数更改元素的背景图像。 得到它与Select元素一起工作,但是被单选按钮搞定了。

感谢您的帮助!

使用选择框

<div id="imagechange"></div>

    <select class="logo">
    <option data-image="url(http://stackoverflow.com/image1)">image1</option>
    <option data-image="url(http://stackoverflow.com/image2)">image2</option>
    <option data-image="url(http://stackoverflow.com/image3)">image3</option>
    </select>


    <script>
    $('.logo').on('change', function () {
    $("#logo").css("background-image", ($('option:selected', this).data("image")));
    });
    </script>  

无法使用单选按钮

<div id="imagechange"></div>

<input name="test" class="swatch" type="radio" data-image="url(http://stackoverflow.com/image1)">image1<br>
<input name="test" class="swatch" type="radio" data-image="url(http://stackoverflow.com/image2)">image2<br>
<input name="test" class="swatch" type="radio" data-image="url(http://stackoverflow.com/image3)">image3<br>


<script>
$('.swatch').on('change', function () {
$("#imagechange").css("background-image", ($('.swatch:checked', this).data("image")));
});
</script>  

2 个答案:

答案 0 :(得分:1)

问题是错误地使用context参数。

$('.swatch:checked', this)相当于$(this).find('.swatch:checked')

但是,由于thisswatch,因此在收音机中找不到后代,而您的选择器无法返回任何匹配项。

我个人建议总是使用find()而不是上下文参数,因为它更容易阅读。使用context参数没有性能优势,因为它无论如何都会在内部使用find()

此外,无线电的change()事件仅在已检查的无线电上触发,因此您应该能够:

$('.swatch').on('change', function () {
   $("#imagechange").css("background-image",$(this).data("image"));
});

答案 1 :(得分:0)

在你的函数中尝试不使用“this”。

$("#imagechange").css("background-image", ($('.swatch:checked').data("image")));
相关问题