实现PHP逻辑到jQuery

In a system I have 3 users, Ben, Shane and Payne, the site functions normally for all users and also have same Menu system. However I am tasked to add one Menu item from core and be visible only for Ben.

So, I added Candy in the Menu item as Ben is kid, but now I cannot change the core in PHP saying

if('Ben' === $user->name) {
  // Show the Candy Menu
}

But I want Candy menu to show only for Ben and hide it from others.

How do I do it with jQuery?

I am not looking to mess up the PHP code like:

<?php if('Ben' === $user->name):?>
  <script ></script>
<?php endif; ?>

I want some logic of PHP to be implemented with jQuery, so, I don't mess with PHP code, instead implement the logic in jQuery. Something like:

//I am mixing PHP and jQuery here, I know it doesn't work but this is what I am looking for.
if('user' === 'Ben') {
  $('#CandyMenu').show();
}

How do I do it?

You will have to make some kind of PHP change, otherwise your JS has no way of knowing who the current user is.

If you just mean you don't want to mix PHP in the middle of your Javascript code, you could have some one-off PHP at the top of the document that sets up any globals:

<script>
var myAppGlobals = {};

myAppGlobals.showCandyMenu = <?php echo ($user->name === 'Ben' ? 'true': 'false'); ?>;
// or
myAppGlobals.userName = '<?php echo addslashes($user->name); ?>';
</script>

and then use

if (myAppGlobals.showCandyMenu)
    $("#CandyMenu").show();

// or

if (myAppGlobals.userName === 'Ben')
    $("#CandyMenu").show();

from your Javascript later on. You're still mixing PHP and JS, but at least you're doing it all up the top instead of mixed in all over the place.

Of course, bear in mind that any method you use to set the visibility of a menu from the client side is open to abuse – anyone with JS knowledge would be able to delve in and display that menu option. Whether that's a problem or not is up to you.

You can store the value in a JavaScript variable:

var user = '<?php echo $user->name; ?>';

$('#CandyMenu').toggle(user === 'Ben');

However, this should be done on the server-side, when an element is hidden, it's still on the page. using jQuery(JavaScript) is not the proper way of doing this, specially if you are echoing sensitive data.