简体   繁体   中英

jQuery/JS - Hiding specific dynamically created elements/buttons

I've built a simple chat application with message rating functionality. I want to prevent self-ratings by hiding the corresponding rating buttons. So on Bob's screen for example there should be no rating buttons next to Bob's messages.

I've tried to realize that by comparing the #name and #user-name. If they are equal, the rating buttons should be hidden. But it looks like I'm doing that not correctly.

That main problem is that a message div .standard-msg is created dynamically so I need something like "on-dom-change".

Every help appriciated.

 $("#standard-msg").on("DOMSubtreeModified", function() { $('.standard-msg').each(function() { if ($('#name').val() == $(this).find('#user-name').text()) { $('button').hide(); } }); }); 
 <div id="chat-wrapper" class="wrapper"> <div class="message-box" id="message-box"> <div class="standard-msg"> <button class="rating like-btn">Like</button> <button class="rating dislike-btn">Dislike</button><span style="color:#FF7000" class="user-name">Bob</span> : <span class="user-message">hi</span> </div> <div class="standard-msg"> <button class="rating like-btn">Like</button> <button class="rating dislike-btn">Dislike</button><span style="color:#FF7000" class="user-name">Alice</span> : <span class="user-message">hello</span> </div> </div> <div class="panel"> <input type="text" name="name" id="name" placeholder="Your Name" maxlength="10" /> <input type="text" name="message" id="message" placeholder="Message" maxlength="80" /> <button id="send-btn" class="btn">Send</button> </div> </div> 

If the buttons were added to the page after the page has loaded then they won't respond to any code (in the page before they were created) that references them. This is because new event listeners are added for the buttons when they are created and somehow they don't pickup on any code older than they are.

To get around this quirk, just add the code dynamically as you add the buttons to the page and it should work.

eg

var s = "$('#standard-msg').on('DOMSubtreeModified', function() { $('.standard-msg').each(function() { if ($('#name').val() == $(this).find('#user-name').text()) { $('button').hide(); } }); }); ";

then append to the page,

$("body").append(s);

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