如何在JavaScript中实现类似PHP常量MODE_B2B_B2C的条件判断
Got it, let's break down how to replicate that PHP conditional check in JavaScript. First, your PHP code checks if the MODE_B2B_B2C constant is set to 'true', then adds a table header cell to your content. Here's how to do the same in JS, including getting that PHP constant into your client-side code.
First: Pass the PHP Constant to JavaScript
Since JavaScript runs in the browser, you need to inject the value of MODE_B2B_B2C from your PHP backend into your JS script. You can do this directly when rendering the page:
<script type="text/javascript"> // Pull the PHP constant into a JS variable const MODE_B2B_B2C = '<?php echo MODE_B2B_B2C; ?>'; // Rest of your JS code goes here... </script>
If MODE_B2B_B2C is a boolean in PHP (not a string), you can output it as a JS boolean instead for cleaner comparisons:
const MODE_B2B_B2C = <?php echo MODE_B2B_B2C ? 'true' : 'false'; ?>;
Second: Write the Conditional Logic in JS
Now that you have the constant available, here's how to mirror your PHP logic:
Option 1: Dynamically Add the Table Cell (Like Your PHP Code)
If you want to add that table header cell to an existing row in the DOM, use this:
// Grab the table row you want to modify (adjust the selector to match your HTML) const targetRow = document.querySelector('tr'); if (MODE_B2B_B2C === 'true') { // Or just `=== true` if you used the boolean version // Create the <td> element const headerCell = document.createElement('td'); // Set its text (inject the translated text from PHP here too) headerCell.textContent = '<?php echo $this->app->getDef('table_heading_customers_group'); ?>'; // Add the cell to the row targetRow.appendChild(headerCell); }
Option 2: Use the Condition in Your Existing JS Function
Looking at your snippet, you have a quantitydiscount_row variable. If you need to use the condition within that context, here's an example:
var quantitydiscount_row = <?php echo $i; ?>; // Check the mode and run your logic if (MODE_B2B_B2C === 'true') { // Do whatever you need here—like update a DOM element, calculate values, etc. console.log('B2B/B2C mode is active'); }
Quick Tip:
In JavaScript, always prefer strict equality (===) over loose equality (==) to avoid weird type coercion bugs. It's the same best practice as using === in modern PHP.
内容的提问来源于stack exchange,提问作者Zigoto

