因此,当我单击添加按钮时,它会检查输入字段中是否有文本,然后为它创建一个div,然后将+1添加到计数器。问题是反击;它只会增加+1,然后再次点击时不会执行任何操作。当我删除一个div它做-1就好了。所以是的,不会超过1或-1。
网站:
功能:
function validateForm()
{
var x=document.forms["forming"]["texting"].value;
if (x==null || x=="")
{
alert("Get it together! You need to have text in there!");
return false;
}
else
{
var clone = $('#theDiv')
.clone()
.attr('id','')
.show()
.append(
$('<div>').html(
$('#textI2').val()
).addClass('futureEditor')
);
$('#hold').append(clone)
var x = 0;
x += 1;
document.getElementById( "clicked" ).value = x;
return false;
}
}
点击链接:
<form id="forming" name="forming" onsubmit="return validateForm()" method="post">
计数器:
<p>You have <input id="clicked" size="3" onfocus="this.blur();" value="0" > Stuffs. </p>
答案 0 :(得分:2)
让你的计数变量全局
var count = 0;
function validateForm() {
var x = document.forms["forming"]["texting"].value;
if (x == null || x == "") {
alert("Get it together! You need to have text in there!");
return false;
}
else {
var clone = $('#theDiv').clone().attr('id', '').show().append(
$('<div>').html(
$('#textI2').val()).addClass('futureEditor'));
$('#hold').append(clone)
count++;
document.getElementById("clicked").value = count;
return false;
}
}
答案 1 :(得分:2)
var x = 0;
导致问题。您每次调用validateForm()
时声明x为0并添加1。因此,文本框的值每次都设置为1。这是固定代码:
var x = 0;
function validateForm() {
if (x==null || x=="") {
alert("Get it together! You need to have text in there!");
return false;
}
else {
var clone = $('#theDiv')
.clone()
.attr('id','')
.show()
.append(
$('<div>').html(
$('#textI2').val()
).addClass('futureEditor')
);
$('#hold').append(clone)
x++;
document.getElementById( "clicked" ).value = x;
return false;
}
}
答案 2 :(得分:1)
你总是将x初始化为0
var x = 0;
这就是显示alwasys 1的原因。
所以创建一个全局变量并使用它。喜欢
var itemsCount = 0;
并在validateForm()函数中替换代码行
var x = 0;
x += 1;
document.getElementById( "clicked" ).value = x;
到
itemsCount += 1;
document.getElementById( "clicked" ).value = itemsCount ;