从while循环中的按钮获取值

时间:2016-02-05 23:44:05

标签: javascript php button

我有一个带有多个按钮的while循环,它们是这样的:

<button onclick="confirmDelete()" value="<?php echo $game['id'];?>" name="deleteButton">Delete </button> 

接下来是以下确认消息:

<script>
function confirmDelete() {

var r = confirm(" **HERE I WANT THE ID TO START WITH** ");
if (r == true) {
    // delete
} else {
    // cancel
}
}
</script>

每个按钮都有自己的值,但现在我想在我的javascript中点击该按钮时的值。我试过很多东西,但不能让它起作用。

编辑:

如果有人能告诉我一个更好/更简单的方法,欢迎您告诉我

2 个答案:

答案 0 :(得分:1)

将您的函数与this参数一起使用,即:

<button onclick="confirmDelete(this)" id="myButton" value="someId" name="deleteButton">Delete </button> 
<script>
function confirmDelete(elem) {
var r = confirm(" **HERE I WANT THE ID TO START WITH** ");
var theValue = elem.value; //someId
var theId    = elem.id; //myButton
if (theValue == "True") {
    alert("True")
} else {
    alert("False")
}
}
</script>

现场演示:
http://codepen.io/anon/pen/QyZgqO

答案 1 :(得分:1)

将游戏ID作为参数

传递给confirmDelete函数
<button onclick="confirmDelete(<?php echo $game['id'];?>)" name="deleteButton">Delete </button>

<script>
    function confirmDelete(id) {

        var r = confirm(id);
        if (r == true) {
            // delete
        } else {
            // cancel
        }
    }
</script>