欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

django視圖后點(diǎn)擊更改按鈕

我有這個(gè)使用htmx的表單,我試著寫(xiě)hx-swap:innerhtml,但是它只是寫(xiě)響應(yīng)而不是按鈕:

<form id="follow-form" hx-post="{% url 'main:follow_toggle' account.id %}">
        {% csrf_token %}
        {% if request.user in account.followers.all %}
        <button type="submit" id="follow-button" class="btn btn-secondary rounded-pill">????</button>
        {% else %}
        <button type="submit" id="follow-button" class="btn btn-success rounded-pill">????</button>
        {% endif %}
      </form>

這個(gè)觀點(diǎn)是:

class FollowToggleView(generic.View):
    def post(self, request, account_id):
        user_to_toggle = get_object_or_404(Account, id=account_id)
        if user_to_toggle in request.user.following.all():
            request.user.unfollow(user_to_toggle)

            return HttpResponse('User unfollowed successfully')
        else:
            request.user.follow(user_to_toggle)
            return HttpResponse('User followed successfully')

我試過(guò)這個(gè)js,但是它不能改變按鈕類:

<script>
      const followButton = document.getElementById('follow-button');
    
      // Handle the AJAX response to update the button text and class
      document.addEventListener('htmx:afterSwap', (event) => {
        if (event.detail.target.id === 'follow-toggle') {
          const response = event.detail.xhr.response;
    
          if (response.is_following) {
            followButton.innerText = '????';
            followButton.classList.remove('btn-success');
            followButton.classList.add('btn-secondary');
          } else {
            followButton.innerText = '????';
            followButton.classList.remove('btn-secondary');
            followButton.classList.add('btn-success');
          }
        }
      });
    </script>

在您的Javascript代碼中,您試圖使用getElementById('follow-button ')訪問(wèn)follow按鈕。在htmx中,由于頁(yè)面重新加載,按鈕元素可能在表單提交后被替換,對(duì)按鈕元素的引用也可能丟失。

您可以修改您的Javascript代碼,以便按鈕元素即使在表單提交后仍然存在:

document.addEventListener('htmx:afterSwap', (event) => {
  const followButton = event.target.querySelector('#follow-button');
  if (followButton) {
    const response = event.detail.xhr.response;

    if (response.is_following) {
      followButton.innerText = '????';
      followButton.classList.remove('btn-success');
      followButton.classList.add('btn-secondary');
    } else {
      followButton.innerText = '????';
      followButton.classList.remove('btn-secondary');
      followButton.classList.add('btn-success');
    }
  }
});

同樣,在Django視圖中,您將返回一個(gè)帶有純文本消息的HTTP響應(yīng),而不是包含is_following標(biāo)志的JSON響應(yīng)。