[英]Limit inserting the element to the page
I'm trying to limit inserting elements to the page: 我试图限制向页面插入元素:
<script type="text/javascript">
$(function() {
var i = 1;
//allow only 3 elements
if (i < 4) {
$('#add').click(function() {
var add_input = '<input type="file" />'
var add_link = '<a href="#" class="remove">Remove</a>'
$('body').append('<p>' + add_input + add_link + '</p>');
});
i++;
}
$('.remove').live('click', function() {
$(this).parent('p').remove();
});
});
</script>
But I can still add element a lot more than 4. 但是我仍然可以添加4个以上的元素。
You need to check your variable i
within your event handler. 您需要在事件处理程序中检查变量i
。
$('#add').click(function() {
if(i < 4){
var add_input = '<input type="file" />'
var add_link = '<a href="#" class="remove">Remove</a>'
$('body').append('<p>' + add_input + add_link + '</p>');
i++;
}
});
And you should decrease i
within your live()
handler. 并且您应该在live()
处理函数中减少i
。
See a working example : http://jsfiddle.net/CtGgg/ 参见工作示例: http : //jsfiddle.net/CtGgg/
You could count the number of elements already on the page and limit it that way. 您可以计算页面上已经存在的元素数,并以此方式进行限制。 Personally, I like treating the DOM itself as the canonical representation of user state. 就个人而言,我喜欢将DOM本身视为用户状态的规范表示。 If that's important to you, you could do something like the following, even though it's a little less performant: 如果这对您很重要,即使性能稍差,您也可以执行以下操作:
$('#add').live('click', function (evt) {
if ($('input[type=file]').length < 4) {
$('body').append('<p><input type="file"> <a href="#" class="remove">Remove</a></p>');
}
evt.preventDefault();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.