0

想从下面的 jsbin 链接代码中一次只选择一张图片

http://jsbin.com/avaxay/1/edit

代码:

$(function() {

  $("img").click(function() {

    $("img").not(this).removeClass("hover");

    $(this).toggleClass("hover");

  });

  $("#btn").click(function() {

    var imgs = $("img.hover").length;    
    alert('there are ' + imgs + ' images selected');

  });

});

谢谢....

4

4 回答 4

3

您可以使用以下代码:

  $("img").click(function() {

    $("img").not(this).removeClass("hover");

    $(this).toggleClass("hover");

  });

hover从所有图像中删除该类(使用该not方法删除的当前除外)并为当前切换该类。

更新 jsbin:http: //jsbin.com/avaxay/36/edit

于 2013-06-14T06:18:13.257 回答
1
  $("img").click(function() {

    $('ul > li > img').removeClass("hover);
    $(this).addClass("hover");

  });
于 2013-06-14T06:16:33.280 回答
1
$("img").click(function() {
    $("img.hover").attr('class', '');
    $(this).toggleClass("hover");

  });

我希望这是你所期望的

于 2013-06-14T06:17:41.747 回答
0

You could use jQuery.one() function or jQuery.off()

I think the best solution here could be the use of jQuery.off('click')

$("img").click(function(){
   $("img").off('click');
});

and then, re-enable when the alert is triggered

Example: http://jsfiddle.net/c7puz/

JS

// function to do something when the click is trigger
function enableSelect(){
    $("img").click(function(){
      $(this).toggleClass("hover");
      // toggle off the click, so only first one will work,
      // until the function is called again
      $("img").off('click');
    });
}enableSelect();

$("#btn").click(function(){
    var pos = $("img.hover").parent().index();
    if(pos > -1){
        // tell us the selected image to work with
        alert('The selected image is at position: ' + pos );
        // clear the hover state
        $("img").removeClass("hover");
        // and enable the click again
        enableSelect();
    } else {
        alert('no image selected');
    }
});

Good luck ;-)

于 2013-06-14T07:06:34.017 回答