这是您要求的示例代码。有两个具有不同 href 属性的 link 元素。单击时,将向指定为 href 的任何内容触发 ajax 请求,成功后,相应的范围将填充字符串并显示 3 秒。
<a onclick='return eachlike(this)' href="https://www.jamarkoho.com/liked/1" class="btn btn-outline-dark btn-sm">
<i class="far fa-thumbs-up me-1"></i>
Like <span class="here"></span>
</a>
<a onclick='return eachlike(this)' href="https://www.jamarkoho.com/liked/2" class="btn btn-outline-dark btn-sm">
<i class="far fa-thumbs-up me-1"></i>
Like <span class="here"></span>
</a>
<script>
function eachlike(thislike) {
$.ajax({
type: 'GET',
url: $(thislike).attr('href'),
success: function(response) {
$(thislike).find('.here').html('Done!').show().delay(3000).fadeOut();
}
});
return false;
}
</script>
要实际切换 href(喜欢/不喜欢),请使用类似以下内容:
<a onclick='return eachlike(this)' href="https://www.jamarkoho.com/liked/1" data-toggle-href="https://www.jamarkoho.com/unlike/1" class="btn btn-outline-dark btn-sm">
<i class="far fa-thumbs-up me-1"></i>
Like <span class="here"></span>
</a>
<a onclick='return eachlike(this)' href="https://www.jamarkoho.com/liked/2" data-toggle-href="https://www.jamarkoho.com/unlike/2" class="btn btn-outline-dark btn-sm">
<i class="far fa-thumbs-up me-1"></i>
Like <span class="here"></span>
</a>
<script>
function eachlike(thislike) {
$.ajax({
type: 'GET',
url: $(thislike).attr('href'),
success: function(response) {
$(thislike).find('.here').html('Done!').show().delay(3000).fadeOut();
toggleHref(thislike);
}
});
return false;
}
function toggleHref(thislike) {
let currentHref = $(thislike).attr('href');
let newHref = $(thislike).data('toggle-href');
$(thislike).attr('href', newHref);
$(thislike).data('toggle-href', currentHref);
}
</script>
第二个功能在
href
和新属性 data-toggle-href
之间切换。