Change to a option on click image with jQuery

2019-06-10 09:17发布

问题:

I would like to change option into select if I click on some image. Value of option is a unique ID of parameter. I would like to use jQuery but I'm beginner and I don't know how. Now I have this:

$(document).ready(function () {
  $('img').click(function(){
    $("option:selected").removeAttr("selected");
    $('option[value="' + $(this).attr("alt") + '"]').attr('selected', true);
  });
});

But it doesn't work. All source are here http://jsfiddle.net/EKaKw/2/. Answer into jsfiddle would be best. Thanks advance.

回答1:

the first, you havn't selected jquery library,

the second, there is an easier way to change selection in jquery

$(document).ready(function () {
    $('img').click(function(){
        $('select').val($(this).attr('alt'));
    });
});

fiddle: http://jsfiddle.net/73VmN/



回答2:

You have not included Jquery library.

$(document).ready(function () {
  $('img').click(function(){
    $("option:selected").removeAttr("selected");
     $('option[value="' + $(this).attr("alt") + '"]').attr('selected', 'selected');
 });
});