0

以下のjsbinリンクコードから一度に1つの画像のみを選択したい

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() {
    $("img.hover").attr('class', '');
    $(this).toggleClass("hover");

  });

これがあなたの期待通りであることを願っています

于 2013-06-14T06:17:41.747 に答える
0

jQuery.one()関数またはjQuery.off( )を使用できます

ここでの最善の解決策は、jQuery.off('click')

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

次に、アラートがトリガーされたときに再度有効にします

例: 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');
    }
});

幸運を ;-)

于 2013-06-14T07:06:34.017 に答える