首页 > 解决方案 > 自定义按钮仅在 HTML 列表中的第一个元素处起作用

问题描述

我正在创建一个包含列表的 Django HTML 模板,每个列表都应该有一个自定义按钮,因为存在的许多列表元素必须有一个自定义按钮。该按钮应该在活动和非活动之间切换。使用 JavaScript 创建此切换后,它仅适用于列表的第一个元素。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dashboard</title>

     {% load static %}
     <link rel="stylesheet" href="{% static 'css/style.css' %}">
     <script src="{% static 'js/dashboard.js' %}">
     </script>
</head>
<body>

   
   {% for all_users in users %}     
    <li>{{all_users}}
        
         <button onclick="handleToggle()" id="switchName" type="submit"> Switch To Active State
        </button>
        
    </li>  
    {% endfor %}

<p> this is all {{users}}</p>
    <p>there are {{usersCount}} users in the admin and its presently {{now}}</p>

    <form method="get">
      {{filterUsers.form.as_p}}
        <button type="submit">Search</button>
     </form>
     <ul>
        {% for user in filterUsers.qs %}
          <li>{{user}}</li>
        {% endfor %}
        </ul>
</body>
</html>


我对应的 JavaScript 看起来像

function handleToggle() 
{
    var elem = document.getElementById("switchName");
    if (elem.innerHTML=="Switch To Active State") 
    elem.innerHTML = "Switch To Inactive State";
    else elem.innerHTML = "Switch To Active State";
}

PLease any suggestions and corrections are veery much welcom

标签: javascripthtmldjangodjango-templates

解决方案


function handleToggle() 
{
    var elem = document.getElementById("switchName");
    if (elem.innerHTML=="Switch To Active State") {
      elem.innerHTML = "Switch To Inactive State";
    }
    else {
      elem.innerHTML = "Switch To Active State";  
    }
}

你需要有括号!尝试这个


推荐阅读