繁体   English   中英

如何在 Javascript 中使用 hide()

[英]How to use hide() in Javascript

我试图隐藏一个 div,我将其 id 存储在一个名为“post_container_id”的变量中。 我的代码是:

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);
      });
};

这不会隐藏 div。 它也不会抛出任何错误。 该功能确实被触发(我通过登录控制台进行了检查)。 我究竟做错了什么?

这里有一个错误:

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

您只是在声明该函数,您还应该调用它:

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

此外,回调在这种情况下是无用的,您可以将其解决为:

 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>

您还可以使用 vanilla JavaScript 通过更改样式显示属性来直接隐藏/显示元素。 如下

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"

暂无
暂无

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

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