简体   繁体   中英

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. When I have 10 blog posts, it only shows for the first (or last) post.

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.

<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. Best practice is not to create the element in the first place based on your userid.

<?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. Note that the id attribute must be unique, so the class attribute should be used instead of 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.

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