具有Jquery功能的唯一整数ID

时间:2018-09-03 10:00:02

标签: jquery

我有一个使用EJS生成动态html内容的文件,ID也是如此。我创建的动态ID的格式为“ project_0”。我想知道在使用这些ID时如何访问该函数,而不必为每个ID重复代码。 App.js(NODE)


app.get("/test",function(req,res)
{
    res.render('test',{data:[{'project':'CMS'},{'project':'LMS'}, 
    {'project':'Web'}]})
})

test.ejs


<!doctype html>
<html>
    <head>
        <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script>
    </head>
    <body>
        <% for(var i=0; i<data.length; i++) {%>

        <div id="project_<%=i%>" style="color:red;display:block"> 
    <%=data[i].project%>
        </div>

         <div id="hidden_<%=i%>" style="display:none">
     This is my last project
         </div>

         <button id="button_<%=i%>">click Me!</button>
         <br/>
         <%}%>
    </body>
    <script>
        $(function(){
            $("#button_0").click(function(){
            $("#hidden_0").show()
            $("#project_0").css("color","blue")
         })

         $("#button_1").click(function(){
            $("#hidden_1").show()
            $("#project_1").css("color","blue")
         })

         $("#button_2").click(function(){
            $("#hidden_2").show()
            $("#project_2").css("color","blue")
         })
        })
    </script>
</html>

1 个答案:

答案 0 :(得分:0)

简单的答案是永远不要使用增量id属性。它们是反模式。

使用通用类将HTML结构分组在一起,然后在JS中使用DOM遍历来关联相关元素,如下所示:

$(function() {
  $(".button").click(function() {
    var $container = $(this).closest('.container');
    $container.find('.hidden').toggle()
    $container.find('.project').toggleClass('active');
  });
})
.project {
  color: red;
  display: block;
}

.hidden {
  display: none;
}

.project.active {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- repeated as many times as needed in your loop... -->
<div class="container">
  <div class="project">
    data[i].project
  </div>
  <div class="hidden">
    This is my last project
  </div>
  <button class="button">click Me!</button>
</div>

<div class="container">
  <div class="project">
    data[i].project
  </div>
  <div class="hidden">
    This is my last project
  </div>
  <button class="button">click Me!</button>
</div>
<div class="container">
  <div class="project">
    data[i].project
  </div>
  <div class="hidden">
    This is my last project
  </div>
  <button class="button">click Me!</button>
</div>

还要在这里注意使用CSS类而不是使用css()创建内联样式。