繁体   English   中英

获取包含php变量的js函数的按钮名称或值

[英]getting a button name or value to the js function that contains a php variable

嗨,我是Javascript新手,并试图通过检索单击按钮的值或名称将使用PHP计算的值发送到JS函数。

PHP文件:

<html>
<head>
<script src="js/script.js">
</script>
</head>
<body>
<table width="500" align="center" cellpadding="5" cellspacing="0" border="0">
    <tr>
        <td width="10%"><strong>#</strong></td>
        <td width="30%"><strong>Name</strong></td>
        <td width="10%"><strong>Price</strong></td>
        <td width="10%" align="center" colspan="3"><strong>Quantity</strong></td>
    </tr>
    <?php 
$shopgold = $userRow['gold']; 
$pricegold = 255; 
$maxkopengold = $shopgold / $pricegold;
?>
    <tr>
        <td><img src="metals/gold.png" width="100%"></td>
        <td>Gold</td>
        <td><?php echo $pricegold; ?></td>
        <td><button name="goldValue" onClick="countDownGold()" value="<?php echo $maxkopengold; ?>">-</button></td>
        <td align="center">(<span id="goldValue">0</span>/<?php echo $maxkopengold; ?>)</td>
        <td><button name="goldValueUp" onClick="countUpGold()" value="<?php echo $maxkopengold; ?>">+</button></td>
    </tr>
</table>
</body>
</html>

js / script.js

function countUpGold() {
    var currentVal = document.getElementById("goldValue").innerHTML;
    var maxVal = jQuery(this).attr("name");
    var elements = document.getElementsByName ("goldValueUp");
        newVal = currentVal;
        alert(this.value);
        newVal++;
    if (currentVal < maxVal) {
        newVal++;
    }
    document.getElementById("goldValue").innerHTML = newVal;
}
function countDownGold() {
    var currentVal = document.getElementById("goldValue").innerHTML;
        addVal = 1;
        var newVal = 0;
    if (currentVal > 0) {
        newVal = currentVal - addVal;
    }
    document.getElementById("goldValue").innerHTML = newVal;
}

我使+-按钮正常工作,但是现在我试图设置最大值(可用货币/对象的价格),然后将其设置为PHP变量,该变量将用作按钮的名称或值。 buttonname.value

我希望我有道理。 提前致谢

this是指内联单击处理程序中的window对象,因此jQuery(this).attr("name")将不起作用。 你需要通过即当前元素上下文this内联单击处理程序。

<button name="goldValueUp" onClick="countUpGold(this)" value="<?php echo $maxkopengold; ?>">+</button>

并使用它

function countUpGold(elem) {
    var maxVal = elem.getAttribute('name'); //jQuery(elem).attr("name");
    var value = elem.value;
    //Your existing code
}

但是,当您使用jQuery时,我建议您使用不引人注目的事件处理程序。 分配一个通用类,即goldValueUp然后使用它绑定事件处理程序。

的HTML

<button name="goldValueUp" class="goldValueUp" value="<?php echo $maxkopengold; ?>">+</button>

脚本

$(function(){
    $('.goldValueUp').on('click', function(){
        var maxVal = jQuery(elem).attr("name");
        //Some operations
    })
})

暂无
暂无

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

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