简体   繁体   English

无法让我的 Javascript 函数在 PHP foreach 循环中多次运行

[英]Can't get my Javascript function to run more than once in a PHP foreach loop

I am trying to build a simple 'blog' that myself or a moderator can remove by calling a delete function.我正在尝试构建一个简单的“博客”,我自己或版主可以通过调用删除函数来删除它。 However, I only want the delete button to show for administrators.但是,我只希望向管理员显示删除按钮。 I created a function to validate the user, that is working fine.我创建了一个函数来验证用户,它工作正常。 However, I am not familiar enough with Javascript to know whether to use window.onload or onopen or onchange, or how to attach the function to my Foreach loop to run for each blog post I have.但是,我对 Javascript 不够熟悉,不知道是使用 window.onload 还是 onopen 或 onchange,或者如何将函数附加到我的 Foreach 循环以针对我拥有的每篇博文运行。 When I have 10 blog posts, it only shows for the first (or last) post.当我有 10 篇博客文章时,它只显示第一篇(或最后一篇)文章。

I have tried adding the "onload / onopen / onchange" commands to the body, to the foreach loop, and to my tags to see if it responds differently.我已经尝试将“onload/onopen/onchange”命令添加到主体、foreach 循环和我的标签中,以查看它是否有不同的响应。

<script>
    function ShowDelete()
{
    var x = document.getElementById("Delete");
        if (userid === "1") {
            x.style.display="block";
    }
    else {
        x.style.display="none";
    }
}
window.onload = ShowDelete;
</script>
<?php foreach ($entries as $entry) : ?>
  <?php if ($userid == 1) { ?>
<input type="submit" id="btnDelete" value="Delete Post" />
<?php } ?>
<?php endforeach; ?>

Ok Thank you all so much for the responses, I simply input the decision statement inside the loop to determine whether to show or skip.好的,非常感谢大家的回复,我只是在循环内输入决策语句来确定是显示还是跳过。 Thanks a ton!!!万分感谢!!!

You are creating an HTML input and then hiding it.您正在创建一个 HTML 输入,然后将其隐藏。 Best practice is not to create the element in the first place based on your userid.最佳实践不是首先根据您的用户 ID 创建元素。

<?php foreach ($entries as $entry) : ?>
    /* Check for userid here and create delete element if condition is met */
<?php endforeach; ?>

No need to call a function multiple times to set the style.无需多次调用函数来设置样式。 In your onload event, capture all of the <input/> elements by class name and set your display style.在您的onload事件中,按类名捕获所有<input/>元素并设置您的display样式。 Note that the id attribute must be unique, so the class attribute should be used instead of id .请注意, id属性必须是唯一的,因此应使用class属性而不是id

 const userid = "0"; window.addEventListener('DOMContentLoaded', () => { let inputs = document.getElementsByClassName("Delete"); Array.from(inputs).forEach(input => { input.style.display = userid === "1" ? "block" : "none"; }); });
 <input type="submit" class="Delete" value="Delete Post" /> <input type="submit" class="Delete" value="Delete Post" /> <input type="submit" class="Delete" value="Delete Post" />

It may also be of benefit to take a look at this post regarding load listeners.查看有关load侦听器的这篇文章也可能会有所帮助。

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

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