我有一些看起来像这样的 jquery,
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('title');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
}
});
});
我的问题是,如果用户一直点击,那么 .hfeed 会一直向其附加数据。如何限制它只能点击一次?
最佳答案
使用 one
功能:
Attach a handler to an event for the elements. The handler is executed at most once per element
如果您希望该元素仅被点击一次,然后在请求完成后重新启用,您可以:
A) 保留一个状态变量,如果请求当前正在进行则更新,如果是则在事件顶部退出。
B) 使用one
,将您的代码放入函数中,并在请求完成后重新绑定(bind)。
第二个选项看起来像这样:
function myClickEvent() {
var selectedCareer = $(this).attr('title');
var that = this;
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
},
complete: function() {
$(that).one('click', myClickEvent);
}
});
}
$('.career_select .selectitems').one('click', myClickEvent);
关于javascript - jquery点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3636824/