How do I toggle two images using jQuery and radio buttons?

做~自己de王妃 提交于 2020-01-16 18:15:15

问题


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>

and

$(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'
        });
    }
});

回答1:


You have several issues:

  • 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.

Try this:

$(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'
      });
    }
  });
});

Check an example here.




回答2:


if ($("jpgSel:checked").val() == 1) {

should read

if ($("#jpgSel:checked").val() == 1) {

or was that a typo?

Also you may want to use $('#jpgSel:checked') on its own w/out == 1

edit

oh and $("input[@name='jpgSel']").click(function(){ might be better.




回答3:


jpgSel is a name and has to be selected like this

$("[name='jpgSel']:checked") 

although i think it would be easier to scrap that and use the .click() function like so

$("[name='jpgSel'][value='0']").click(function{/*do something*/});
$("[name='jpgSel'][value='1']").click(function{/*do something else*/});


来源:https://stackoverflow.com/questions/2994746/how-do-i-toggle-two-images-using-jquery-and-radio-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!