简体   繁体   English

具有相同类别的动态元素

[英]Dynamic elements with the same class

I'm having some issues regarding dynamically created elements. 关于动态创建的元素,我遇到了一些问题。 I'm trying to creating a page for my site which will display a list of users(which has been passed into my view from the controller). 我正在尝试为我的站点创建一个页面,该页面将显示用户列表(已从控制器传递到我的视图中)。 For each user i've created a div holder, and inside each div I have two h3 tags displaying both the ID and Name of the user. 我为每个用户创建了一个div持有人,在每个div内,我有两个h3标签,分别显示用户的ID和名称。 Each user div also contains a button, which allows a user to be hidden, or shown. 每个用户div还包含一个按钮,该按钮允许隐藏或显示用户。

 <div class="single-user" id="@user.Hidden.ToString()">
     <h3>ID: @user.Id</h3>
     <h3>Name: @user.Forename @user.Surname</h3>
     <span><input type="submit" class="sub-btn" /></span>
 </div>

along with then 'name' and 'id' property I also pass in a 'hidden bool property. 除了“ name”和“ id”属性外,我还传递了“ hidden bool”属性。 This is used to check if a user has been hidden. 这用于检查用户是否已隐藏。 The problem i'm having is that because the elements have been created dynamically, they all share the same classe's and id's, so i'm unable to check if a user is hidden or not. 我遇到的问题是,因为元素是动态创建的,所以它们都共享相同的类和ID,所以我无法检查用户是否隐藏。 I looked online and found a possible solutions, however, it's still not working. 我在网上查看并找到了可能的解决方案,但是它仍然无法正常工作。 Here is my javascript code. 这是我的JavaScript代码。

 <script type="text/javascript">

    $('.single-user').on('click', '.sub-btn', function () {
        if ($('.single-user').has('#True')) {
            console.log("true");
        }
        else {
            console.log("false");
        }
    });

 </script>

Any help would be greatly appreciated. 任何帮助将不胜感激。

<div class="single-user" data-visible="@user.Hidden.ToString()">
     <h3>ID: @user.Id</h3>
     <h3>Name: @user.Forename @user.Surname</h3>
     <span><input type="submit" class="sub-btn" /></span>
 </div>


<script type="text/javascript">

    $(document).on('click', '.sub-btn', function () {
        if ($(this).closest('.single-user').attr('data-visible')=="True") {
            console.log("true");
        }
        else {
            console.log("false");
        }
    });

 </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM