2017-11-25 4 views
2

以下のワンクリック機能からこの#static idを削除して自動的に取得しようとしています「#static」、「#dynamic ...」などのIdsをワンクリック機能に入れています。これにより、ID名を変更するだけで、同じ機能を何度も何度もコピーして貼り付ける手間を省くことができます。さらに、これはコードがきれいに見えるようにします&短いです。クリックした要素のIDを取得し、変数に格納してAJAX呼び出しを行う関数で使用する方法

jQuery(document).ready(function($){ 
// Home Page Static Portfolio Ajax Query 
$(this).one('click', '#static', function(e){ 
    var that = $(this); 
    var id = that.attr('id'); 
    var rel = that.data('rel'); 
    var ajaxurl = that.data('url'); 
    $.ajax({ 
     url : ajaxurl, 
     type : 'POST', 
     data : { 
      rel : rel, 
      action : 'home_filter_' + id + '_portfolios' 
     }, 
     error : function(response){ 
      console.log(response); 
     }, 
     success : function (response){ 
      if (response == '') { 
       $('figure' + id).after('<div class="end_of_testimonial"><h3>You have reached the end of the line</h3><p>No more portfolios to load!</p></div>'); 
      } else { 
       $('.gallery-wrapper').append(response); 
      } 
     } 
    }); 
}); 

任意の助けいただければ幸いです:)あなたのコード行で

+0

それは '.on()'の代わりに '.one()' ...あなたの質問を編集してくださいを使用する方法についてだけではない場合。あなたの問題はよりよく定義できます。 *あなたは何を期待していますか? –

答えて

-2
$(this).one('click', '#static', function(e) 

を使用すると、要素の識別子としてクラスを使用する必要があります。 "id"は一意であり、1つの要素にのみ割り当てる必要があります。

$(body).one('click', '.yourclass', function(e) 

あなたが望むすべての要素にクラスを追加します。

+0

最終コードは $(body).one( 'クリック'、 '.yourclass'、function(e) – mohsinhassan155

+1

です)回答を改善してください:https://stackoverflow.com/posts/47487841/edit –

+1

そのクラスのどれかを 'one()'を使ってクリックすると、そのクラスを持つ他の要素でコードが実行されないようになります – charlietfl

0

あなたは、これは上で動作し、1がクリックされたとき、あなたはone()の代替品として再度要求をしないように、定期的なon()

が別のクラスを追加使用したいすべての要素に共通するクラスを追加することができます機能

$(function() { 
 
    // better to use `document` instead of `this` for readability 
 
    $(document).on('click', '.my-div', function(e) { 
 
    var that = $(this); 
 
    if (that.hasClass('already-clicked')) { 
 
     // bail out 
 
     console.log('Already clicked') 
 
     return 
 
    } else { 
 
     that.addClass('already-clicked'); 
 
     var data = that.data(); 
 
     data.id = this.id; 
 
     console.log(JSON.stringify(data)) 
 
     // do your ajax 
 
    } 
 
    }); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="my-div" id="1" data-rel="rel_1" data-url="url_1">Div one</div> 
 
<div class="my-div" id="2" data-rel="rel_2" data-url="url_2">Div two</div> 
 
<div class="my-div" id="3" data-rel="rel_3" data-url="url_3">Div two</div>

2

あなたはクラスを使用してAjaxの機能にこの方法を呼び出すことができます。あなたのデモコードはここにあります。あなたは、この機能のためにあなたが望むくらいのidを使うことができます。私はそのクラスのすべてのインスタンスを呼び出すためのイベントのドキュメントを使用します。 Fiddel link

jQuery(document).ready(function($){ 
    // Home Page Static Portfolio Ajax Query 
    $(document).on('click', '.clickclass', function(e){ 
     var that = $(this); 
     var id = that.attr('id'); 
     var rel = that.data('rel'); 
     var ajaxurl = that.data('url'); 
      alert(id); 

    }); 
    }); 
関連する問題