2017-11-25 66 views
2

我一直試圖從下面的一次點擊函數中刪除這個#static id,並使用變量自動獲取像'#static#dynamic ...等等,並把它放在一鍵功能。這將通過改變它的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

如果這不只是使用'。對()',而不是'。一()'...請編輯您的問題。你的問題可以更好地定義。你期望的*幫助*是什麼? –

回答

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

在這行代碼中,你應該使用類作爲元素的標識符。 「id」是唯一的,它應該只分配給一個元素。

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

並將該類添加到所需的所有元素。

+0

對不起,最後的代碼是 $(body).one('click','.yourclass',function(e) – mohsinhassan155

+1

改進你的回答:https://stackoverflow.com/posts/47487841/edit。 –

+1

不會因爲使用'one()'單擊任何一個類將會阻止代碼在該類的其他元素上運行 – charlietfl

0

您可以將常用的類添加到所有你想這再次爲更換工作,並使用正on()

添加其他類已被點擊時一個這樣你就不會做出請求one()元素功能

$(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); 

    }); 
    }); 
相關問題