如何使用jQuery和单选按钮切换两个图像? [英] How do I toggle two images using jQuery and radio buttons?

查看:84
本文介绍了如何使用jQuery和单选按钮切换两个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是很漂亮,但是我想您会得到我想要做的.

This isn't pretty, but I think you'll get what I'm trying to do.

<label><input name="jpgSel" type="radio" value="0">jpg 1</label><br />
<label><input name="jpgSel" type="radio" value="1">jpg 2</label><br />
<div id="showjpg"></div>

$(document).ready(function() {
    $("select").change(function () {
           if ($("jpgSel:checked").val() == 1) {
            $('#showjpg').attr({
                src: 'one.jpg',
                 alt: 'one dot jpg'
        });
    }
    else {
            $('#showjpg').attr({
                 src: 'two.jpg',
                 alt: 'two dot jpg'
        });
    }
});

推荐答案

您遇到了几个问题:

  • #showjpg元素是div,您应该在其中具有img元素.
  • 用于绑定change事件的选择器不正确($("select")),应该类似于$("input[name=jpgSel]")
  • 如果将change事件绑定到两个单选按钮,则只需通过this.value即可获取所选元素的值.
  • The #showjpg element is a div, you should have there an img element.
  • The selector you are using to bind the change event is incorrect ($("select")), it should be something like $("input[name=jpgSel]")
  • If you bind the change event to both radio buttons, you can get the value of the selected element simply by this.value.

尝试一下:

$(document).ready(function() {
  $("input[name=jpgSel]").change(function () {
    if (this.value == "0") {
      $('#showjpg').attr({
        src: 'one.jpg',
        alt: 'one dot jpg'
      });
    } else {
      $('#showjpg').attr({
        src: 'two.jpg',
        alt: 'two dot jpg'
      });
    }
  });
});

此处中查看示例.

这篇关于如何使用jQuery和单选按钮切换两个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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