我有一个Jquery表单设置,我可以添加和删除字段:http://jsfiddle.net/beehive/TLJGb/
我不希望能够在此表单上添加超过10个字段.我怎么能做到这一点?
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function() {
$('<p id="yum">beets ' + i + ' <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<h2><a href="#" id="addScnt">Add Another</a></h2>
<div id="p_scents">
<p id="yum">
beets
</p>
</div>
Run Code Online (Sandbox Code Playgroud)
将以下if语句添加到您的代码中......
$('#addScnt').live('click', function() {
if ($(".item", addScnt).length < 9) {
$('<p class="item" id="yum">beets ' + i +' <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
}
return false;
});
Run Code Online (Sandbox Code Playgroud)
首先,我在项目中添加了一个类,以便我可以检测它们.然后我可以算一下是否少于9(+你已经有的那个10)
这是小提琴