0

この Javascript/jQuery コードを要約するのを手伝ってくれる人に感謝することから始めたいと思います。

        jQuery(function() {

            jQuery('#pitem-1').click(function(e) {
                jQuery("#image-1").lightbox_me({centered: true, onLoad: function() {
                    jQuery("#image-1").find("input:first").focus();
                }});

                e.preventDefault();
            });        

            jQuery('#pitem-2').click(function(e) {
                jQuery("#image-2").lightbox_me({centered: true, onLoad: function() {
                    jQuery("#image-2").find("input:first").focus();
                }});

                e.preventDefault();
            });

            jQuery('#pitem-3').click(function(e) {
                jQuery("#image-3").lightbox_me({centered: true, onLoad: function() {
                    jQuery("#image-3").find("input:first").focus();
                }});

                e.preventDefault();
            });

            jQuery('table tr:nth-child(even)').addClass('stripe');
        });

基本的に、各 #pitem-ID は同じ #image-ID をポップアップで開きます。

助けてくれる人にもう一度感謝します。

ジャック

4

4 に答える 4

4

Your functions all look pretty much the same, which is a clue that you should probably move that functionality out into something that can be called:

function createHandler(id) {
    return function (e) {
        $(id).lightbox_me({centered: true, onLoad: function() {
            $(id).find("input:first").focus();
        }});

        e.preventDefault();
    }
};

Then you can use:

 $('#pitem-2').bind('click', createHandler("#image-2"));
于 2012-04-28T00:58:50.200 に答える
3

あなたはできる:

  1. 共通のイベント ハンドラーを使用して複数のオブジェクトをセレクターに結合する
  2. thisイベントをトリガーしたオブジェクトを参照するために使用します
  3. イベントを生成したオブジェクトの ID からイメージ ID を取得します。

これにより、1 つのコードで 3 つのオブジェクトすべてのアクションを処理できます。

jQuery(function() {
    jQuery("#pitem-1, #pitem-2, #pitem-3").click(function() {
        var image$ = $("#" + this.id.replace("pitem", "image"));
        image$.lighbox_me({centered: true, onLoad: function() {
                    image$.find("input:first").focus();
        }});
        e.preventDefault();
    });
    jQuery('table tr:nth-child(even)').addClass('stripe');
});
于 2012-04-28T01:22:02.453 に答える
2
$('[id^="pitem-"]').click(function(e) {
    var numb = this.id.split('-')[1];
    $("#image-"+numb).lightbox_me({centered: true, onLoad: function() {
         $(this).find("input:first").focus();
    }
    });
    e.preventDefault();
});        

$('table tr:nth-child(even)').addClass('stripe');
于 2012-04-28T01:06:15.583 に答える
0

コンテキストがないとわかりにくいですが、それぞれに一意の ID が必要pitemですか? 次のように、ID の代わりに CSS クラスを使用しないのはなぜですか。

<div class="pitem">
<div id="image1"><img ... /></img>
</div>
...
<div class="pitem">
<div id="image3"><img ... /></img>
</div>

次に、jQuery のクラス セレクターを使用して、一度にすべてのクリック機能を追加します。

$(".pitem").click(function(e) {
  var currentItem = e.target;
  ...
  e.preventDefault();
});
于 2012-04-28T01:01:25.820 に答える