获取按钮文本值以确定变量值


Get button text value to determine variable value

我正试图为我的wordpress站点编写一个函数,该函数首先获取按钮的文本值,然后根据该值确定变量的值。

我有三个按钮。每个都有相同的文本值"选择项目"。我编写了一个javascript函数(下面简化为仅显示一个示例),它在单击时将文本值更改为"Selected"。现在我需要找到一种方法来确定按钮的文本值是否更改为"Selected",然后将一个名为$amount的变量更改为新值。我知道jquery可以做到这一点,但我试图避免它的原因是,我需要它来处理特定的wordpress函数,并且在wordpress的functions.php中调用脚本会让人困惑。我试图将按钮更改为输入,并将它们放在一个表单中,这样我就可以尝试$_POST方法,但我对此的理解是,$_POST方法只适用于提交,我需要在任何提交之前更改变量。

 <a href="#" class="selectitem1" type="submit">Select Item</a>
 <a href="#" class="selectitem2" type="submit">Select Item</a>
 <a href="#" class="selectitem3" type="submit">Select Item</a>
$(function() {                     
  $("a.selectitem1").click(function() {  
   $("a.selectitem1").text('Selected');
  });
});
//not sure what to do here
add_filter( 'abcde', 'adjust_amount');
function adjust_amount() {
    if selectitem1 text value is now "Selected"{
    $amount = 50;
    if selectitem2 text value is now "Selected"{
    $amount = 150;
    if selectitem3 text value is now "Selected"{
    $amount = 250;
}

您似乎已经在页面上包含了jQuery,所以我不明白为什么不使用jQuery来设置$amount变量?

获得所需功能的最简单方法如下:

$(function() {                     
    $('a.selectitem1').click(function() {  
        $('a.selectitem1').text('Selected');
        $('a.selectitem2').text('Select item');
        $('a.selectitem3').text('Select item');
        $amount = 50;
    });
    // equivalently for selectitem2 and selectitem3
});

我会使用AJAX:

在您的表单文件中,位于以下位置:

<!DOCTYPE html>
<html>
<body>
<form action=""> 
<input type="button" id="txt1" value="Select Item" name="£10.00" onclick="showValue(this.name)">
<input type="button" id="txt1" value="Select Item" name="£15.00" onclick="showValue(this.name)">
<input type="button" id="txt1" value="Select Item" name="£20.00" onclick="showValue(this.name)">
</form>
<p>Value: <span id="txtValue"></span></p> 
<script>
function showValue(str) {
  var xhttp;
  if (str.length == 0) { 
    document.getElementById("txtValue").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("txtValue").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "getinfo.php?q="+str, true);
  xhttp.send();   
}
</script>
</body>
</html>

然后创建一个名为getinfo.php的文件,并添加以下内容:

 <?php
// Array with names
$a[] = "£10.00";
$a[] = "£15.00";
$a[] = "£20.00";

// get the q parameter from URL
$q = $_REQUEST["q"];
$value = "";
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($value === "") {
                $value = $name;
            } else {
                $value .= ", $name";
            }
        }
    }
}
echo $value === "" , $value;
//More code here for your selected $value variable
?>