简体   繁体   中英

how to shorten a repetitive javascript php code

I am new to javascript. Please help with the following. I have a repetitive block of code that is about 40 "cases" of almost same code - which takes the returned value of wordpress do_shortcode and save to javascript variable (this part works fine).

I'd like to shorten it by some sort of a loop of code that achieved the same functionality. I try not to use COOKIE to pass value to PHP. Please see sample 1st few lines:

switch (id) {
case 1: oh = `<?php echo do_shortcode("[block id=\"oh1\"]"); ?>`;break;
case 2: oh = `<?php echo do_shortcode("[block id=\"oh2\"]"); ?>`;break;
case 3: oh = `<?php echo do_shortcode("[block id=\"oh3\"]"); ?>`;break;
case 4: oh = `<?php echo do_shortcode("[block id=\"oh4\"]"); ?>`;break;`
...
}

jQuery('#id').html(oh);

I have to specify 40 lines like above and have not found another way. Please share your valuable idea. THANKS

What about this (I assume your switch is in Javascript).

oh = '<?php echo do_shortcode("[block id=\"oh_num\"]"); ?>'.replace('_num', yourVariableInSwitch) ;break;`

In this case you don't even need switch statement.

If you have to do if 40 times:

for (var i = 0; i < 40; i++) {
    console.log('<?php echo do_shortcode("[block id=\"oh_num\"]"); ?>'.replace('_num', i);
}

Render switch case statements for javascript with PHP

switch (yourVariable) {
<?php
for ($i = 1; $i < 41; $i++) {
    print 'case ' . $i . ': oh = ' . do_shortcode("[block id=oh'" . $i . "']") . '; break;';
}
?>
}

Using ES6 string interpolation

 const myNumber = 2; const oh = `<?php echo do_shortcode("[block id=\\"oh${myNumber}\\"]"); ?>`; console.log(oh); 

Do it all in PHP:

<?php
for($i=1,$l=41; $i<$l; $i++){
  echo "case $i: oh = ".do_shortcode("[block id='oh$i']").' break;'
}
?>

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