我目前正在为我的阅读更多按钮使用以下代码:
$(document).ready(function() {
$("a.more-link").attr("href", "");
$("a.more-link").attr("onclick", "return false;");
$('.readmore').each(function(index) {
var $link = $(this);
$(".readmore").prependTo('.' + $link.attr("id") + ' > #bottominfo');
});
$('.readmore').click(function() {
var $link = $(this);
if ( $link.attr("alt") == "read more" ) {
$('.' + $link.attr("id") + ' > #maincontent').load($link.attr("title") + ' #mainarticle', function(index) {
$('.' + $link.attr("id") + ' > #maincontent').hide();
$('.' + $link.attr("id") + ' > #maincontent').slideToggle('slow');
});
$('.' + $link.attr("id") + ' > #maincontent').attr("class", $link.attr("id"));
$link.attr('alt','read less');
} else {
$('#'+ $link.attr("id") + ' > .' + $link.attr("id")).hide();
$link.attr('alt','read more');
}
return false;
});
});
我遇到的问题是,如果用户双击(或多次)按钮,它会多次调用该函数。
如何在 .load()
完成之前使按钮不可点击?
最佳答案
最简单的方法是向链接添加一个加载类。我也刚刚对您的代码进行了快速清理。我没有研究它是如何工作的,但我敢肯定,如果你多花点时间,你可以让它更有效率
$(document).ready(function() {
$("a.more-link").attr("href", "")
.attr("onclick", "return false;");
$('.readmore').each(function(index) {
var $link = $(this);
//wouldn't this call all the elements with "readmore" class????
$(".readmore").prependTo('.' + $link.attr("id") + ' > #bottominfo');
});
$('.readmore').click(function() {
var $link = $(this);
//check if it has already been clicked
if($link.hasClass("loading")) return false;
//add the loading class
$link.addClass("loading");
if ( $link.attr("alt") == "read more" ) {
$('.' + $link.attr("id") + ' > #maincontent').load($link.attr("title") + ' #mainarticle', function(index) {
$('.' + $link.attr("id") + ' > #maincontent').hide()
.slideToggle('slow');
//it's done now and we can remove the loading class so we can click it again
$link.removeClass("loading");
}).attr("class", $link.attr("id"));
$link.attr('alt','read less');
} else {
$('#'+ $link.attr("id") + ' > .' + $link.attr("id")).hide();
$link.attr('alt','read more');
//add it here as well
$link.removeClass("loading");
}
return false;
});
});
提示:我注意到您多次调用相同的选择器。始终检查 api doc看看你调用的方法会返回什么。它们中的大多数会返回元素,因此您可以在没有 $()
示例:$("div").hide().slideToggle('slow');
关于javascript - 在 jQuery .load() 完成之前使按钮不可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3996415/