点击时的Javascript增量值(只需点击一下++)

时间:2016-08-13 12:47:23

标签: javascript

当用户点击<button>时,我需要增加一个值。

我的脚本有效,但是当我再次点击时,它会挂在第一个值上。

请问有什么问题?

var global_score;
var current_score;
function question_answer(event_sender, sent_answer) {
	global_score;
	current_score = document.querySelector(".game-current-score-main h2");
	if(sent_answer == "increment") {
		global_score++;
		current_score.innerHTML = "Score:" + global_score;
	}
	else if(sent_answer == "decrement")
	{
		global_score--;
        current_score.innerHTML = "Score:" + global_score;
	}
};

2 个答案:

答案 0 :(得分:2)

你几乎就在那里!所有你需要改变的是将全局值设置为0然后它将起作用

https://jsfiddle.net/nmo5vmd3/

// load as charset 1251
string text = File.ReadAllText("sampleNU.txt", Encoding.GetEncoding(1251));

// save as Unicode
File.WriteAllText("sampleU.txt", text, Encoding.Unicode);
    var global_score = 0; // change here
    var current_score = 0; // change here
    function question_answer(event_sender, sent_answer) {
    	global_score; // you do not need this line cause it does nothing
    	//current_score = document.querySelector(".game-current-score-main h2");
    	if(sent_answer == "increment") {
    		global_score++;
    		current_score.innerHTML = "Score:" + global_score;
    	}
    	else if(sent_answer == "decrement")
    	{
    		global_score--;
            current_score.innerHTML = "Score:" + global_score;
    	}
        console.log(global_score); // you do not need this line, it does nothing
    };

答案 1 :(得分:1)

var global_score = 0; // initialize
var current_score;
function question_answer(event_sender, sent_answer) {
    global_score; // you do not need this line
    current_score = document.querySelector(".game-current-score-main h2");
    if(sent_answer == "increment") {
        global_score++;
        current_score.innerHTML = "Score:" + global_score;
    }
    else if(sent_answer == "decrement")
    {
        global_score--;
        current_score.innerHTML = "Score:" + global_score;
    }
};