简体   繁体   English

如何在简码中使用javascript变量?

[英]How to use javascript variable in a shortcode?

I made a simple Scratch Card game, but I have a problem with some code section. 我做了一个简单的刮刮卡游戏,但是某些代码段有问题。 How do I use a javascript variable in a WordPress shortcode? 如何在WordPress简码中使用javascript变量?

First i use a random number to define the prize amount. 首先,我使用一个随机数来定义奖金额。


<script>
var arar = [1,2,3,4,5]
selectG = arar[Math.floor(Math.random() * arar.length)];
if (selectG == 1) {
    var amon = 30;
  } else if (selectG == 2) {
    var amon = 50;
  } else if (selectG == 3) {
    var amon = 10;
  } else if (selectG == 4){
    var amon = 1;
  } else {
    var amon = -10;
} 
</script>

Then i pass the amount as "amon" in the shortcode 然后我在短代​​码中将金额作为“ amon”传递

<div class="promo-code"></div>
  [mycred_link amount=amon href="https://example.org/choose-card/" ]Collect the prize[/mycred_link]
</div>

When the button "Collect the prize" is pressed it adds the amount to the user points balance (they are used on site to pay for privileges on the website). 当按下“收集奖品”按钮时,会将金额添加到用户积分余额中(在网站上使用它们来支付网站上的特权)。 However it always add 10 points, no matter what. 但是,无论如何,它总是会增加10点。

I researched it (the plugin is called MyCred) and I found out 10 is the default value to add if the amount is undifined or it returns an error (let's say we pass it a random text like> amount = sdfsdfsdf - it will still add 10 points). 我研究了它(插件称为MyCred),发现10是默认值,如果数量未定义或返回错误(假设我们将诸如> amount = sdfsdfsdf之类的随机文本传递给它,则该默认值仍会添加) 10点)。 If I use an integer it will work adding the amount specified...but I need the amount to by changed by the random value selected from the array 'arar' 如果我使用整数,它将添加指定的数量...但是我需要通过从数组“ arar”中选择的随机值来更改

WordPress shortcode runs at the server side, so you cannot pass js variable into the code. WordPress短代码在服务器端运行,因此您不能将js变量传递到代码中。 But you can generate same random value in php: 但是您可以在php中生成相同的随机值:

$arar = array(
    30,50,10,1,-10
);
$amon = $arar[array_rand($arar, 1)];

and use the result here: 并在此处使用结果:

<div class="promo-code"></div>
  [mycred_link amount=$amon href="https://example.org/choose-card/" ]Collect the prize[/mycred_link]
</div>

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

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