【问题标题】:Using Javascript to change text Content of a button使用 Javascript 更改按钮的文本内容
【发布时间】:2020-11-23 19:30:19
【问题描述】:

大家好,我正在创建一个社交媒体消息应用程序,现在我正在了解创建一个按钮来关注人们的基础知识。

当您单击按钮时,它应该将按钮从“关注”更改为“取消关注”。那么追随者的计数器应该增加 1。

到目前为止,这是我的代码,它没有做任何事情。我没有收到任何错误,但它也没有做任何事情。

有人能弄清楚我做错了什么吗?谢谢

network.js:

   document.addEventListener('DOMContentLoaded', function() {

  document.getElementById('followButton').addEventListener('click', () => follow_user());
  
});

function follow_user() {
    const element = document.getElementById('followButton');
    element.value = "Un-Follow";
    const element2 = document.getElementById('followers');
    element2.textContent += 1;
}

profile.html:

{% extends "network/layout.html" %}
{% block body %}

  <h2>{{user.username}}'s Profile</h2>
  <p id="followers">Followers: {{user.followers}}</p>
  <p>Follows: {{user.follows}}</p>
  {% for newquery in newqueries reversed %}
            <div class="newpost"><p>{{ newquery.body }}</p><p>By: {{ newquery.username }} on: {{ newquery.timestamp }} Likes: {{ newquery.likes }}</p></div>
{% endfor %}
<input type="button" value="Follow" id="followButton">
{% endblock %}

【问题讨论】:

  • 我不确定,但我很快用眼睛扫描了你的代码,我可以在这里看到问题: const element2 = document.getElementById('followers');您尝试使用 id 'followers' 访问元素,但是当您查看 HTML 标记时,没有具有此类 id 的元素,我看到您使用 class="followers" 代替,因此请尝试更改它。
  • 我更新了代码,如您所见,它仍然没有做任何事情。

标签: javascript dom event-handling


【解决方案1】:

您的第一个问题是您的关注者数量没有 ID。您尝试使用 #followers 定位它,但它只有一个类 .followers

您的第二个问题是按钮输入不显示 textContent。他们展示了他们的价值。

const element = document.getElementById('followButton');
element.value = "Un-Follow";

【讨论】:

  • 我更新了上面的代码,但它仍然没有做任何事情。
  • 可能问题出在其他地方,你确定开发者控制台没有错误吗?您在这里也有一个问题: document.getElementByID('followButton') 它应该是 getElementById 而不是 getElementByID 你写的 Id 都是大写的。
  • 好吧,我也改变了它 - 仍然没有。怎么会这样?我以前用过。如何确定它正在使用 network.js 文件?
  • {% 块脚本 %} {% endblock %}
  • 尝试查看开发者的控制台,看看你得到了什么错误,因为你之前的错误导致你的代码停止执行。此外,我们无法在此处使用模板引擎提供帮助,因为没有简单的方法可以复制您的问题,而且问题可能出在其他地方。
【解决方案2】:

尝试这样的事情: const element = document.getElementById("followButton").value="Un-Button Follow" 我认为值应该是按钮在联合国和跟随之间,即取消关注,注意(改变它适合您的代码) 在这里查看这篇文章:https://www.permadi.com/tutorial/jsInnerHTMLDOM/index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多