简体   繁体   中英

How to use hide() in Javascript

I am trying to hide a div the id of which I stored in a variable named 'post_container_id'. My code is:

document.addEventListener('DOMContentLoaded', function() {

    // Add event listener to following button
    document.querySelectorAll('.post-edit').forEach(item => {
        var itemid = item.getAttribute('id').slice(5,)
        item.addEventListener('click', () => edit_post(itemid));
    })
    
  });

function edit_post(itemid) {
    var post_container_id = `#post-container-${itemid}`;
    (function(){
        $(post_container_id).hide(1000);
      });
};

This does not hide the div. It does not throw any error either. The function does get triggered (I checked it by logging to console). What am I doing wrong?

There is a mistake here:

(function(){
  $(post_container_id).hide(1000);
});

You are just declaring the function, you should also call it:

(function(){
  $(post_container_id).hide(1000);
})();

Also, the callback is useless in this case, you can just solve it as:

 function edit_post(itemid) { var post_container_id = `#post-container-${itemid}`; $(post_container_id).hide(1000); }; $("#hide").click(function(){ edit_post(1); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="post-container-1">secret</div> <button id="hide">Click to hide</button>

You can also use vanilla JavaScript to hide/show the element directly by changing the style display property. As follows

function edit_post(itemid) {
    const post_container_id = document.querySelectorAll(`#post-container-${itemid}`);
    post_container_id.style.display = 'none';
};

没有jQuery,

document.getElementById(post_container_id).style.display = "none"

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