简体   繁体   中英

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. Each user div also contains a button, which allows a user to be hidden, or shown.

 <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. 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. I looked online and found a possible solutions, however, it's still not working. Here is my javascript code.

 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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