我正在尝试删除文本框的样式或背景,以便在点击10次后显示内容。我怎么能在Javascript上做到这一点?
这是我的HTML:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
这是我的JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
答案 0 :(得分:2)
问题是tries
是一个局部变量(check
函数的本地变量)。每次调用check
时,都会创建一个名为tries
的新变量并将其初始化为0.
请改为尝试:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(我假设您已经有一些代码在单击元素时调用check
。如果没有,则需要在元素中添加click handler。)
答案 1 :(得分:1)
每次进入此函数时,您都在实例化“尝试”。将变量向上移动到增量位置:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}
编辑:
工作JSFiddle
答案 2 :(得分:0)
将其存储在cookie中:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
答案 3 :(得分:0)
你走了。当你看到警报线有效时,请删除它。
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>