在实际HTML按钮上显示计数器

时间:2015-11-05 04:21:56

标签: javascript html button

我有一个'喜欢'按钮;在按钮下面,我可以显示' like count'。

然而,我希望'喜欢计数'要在实际按钮上显示的值。例如,我希望按钮说:"喜欢5"

如何在按钮上显示文本和变量值?

1 个答案:

答案 0 :(得分:0)

也许你可以使用我所做的代码进行改进。

HTML

<form id = "form" method = "POST">
    <input type = "submit" value = "Like" />
</form>

<br />

<div id = "clicks">
    counter = <label id = "count">0</label> clicks !
</div>

JS

function CountOnFormSubmitEvent(form_id, _callback_)
{
    var that = this, count = 0, callback = _callback_;

    var form = document.getElementById(form_id);
    if(form === null) { return null; }

    var reset = function(){
        count = 0;  
    };

    form.addEventListener("submit", function(evt){
        callback(evt, ++count, reset);
    }, false);
}

//Reseting Process You can delete if you dont want it.
var counter = new CountOnFormSubmitEvent("form", function(event, count, reset_callback){
    event.preventDefault();
    if(count >= 10)
    {
        alert("Reseting the process");
        reset_callback();
    }
    document.getElementById("count").innerHTML = count;
});

这是链接Jsfiddle。

DEMO JSFIDDLE