[英]Trying to write a Javascript class to handle dynamically adding more data to my HTML. Need some guidance
这是我要实现的目标:
的HTML
<fieldset id="addmore">
<p>blah</p>
<a class="remove">remove me</a>
</fieldset>
<a class="add">add more fieldsets</a>
Java脚本
var addmore = new AddMore($('fieldset'));
addmore.buildCache(/*this will pull the innerHTML of the fieldset*/);
// bind the buttons
addmore.bind('add', $('a.add'));
addmore.bind('remove', $('a.remove'));
最近,我发现自己的HTML中包含更多“ addmore”内容,因此我一直在尝试构建一个类,该类可以为我完成所有工作,并且可以在所有项目中重复使用。 希望上面的代码将是我每次必须添加的全部内容,然后其余工作将为我完成。
我一直在为这件事做准备,这是我班上要做的事情:
Javascript类
/*
Class to handle adding more data to the form array
Initialise the class by passing in the elements you want to add more of
Then bind 'add' and 'remove' buttons to the functions and the class will do the rest
*/
/*
Pass the jQuery object you want to 'addmore' of
Ex: var x = new AddMore($('fieldset.addmore'));
*/
function AddMore($element)
{
if (!$element || typeof($element) != 'object')
throw 'Constructor requires a jQuery object';
this.element = $element; // this is a jQuery object
this.cache = null;
}
/*
Supply clean HTML to this function and it will be cached
since the cached data will be used when 'adding more', you'll want the inputs to be emptied,
selects to have their first option selected and any other data removed you don't want readded to the page
*/
AddMore.prototype.buildCache = function(fieldset)
{
if (!fieldset)
throw 'No data supplied to cache';
this.cache = fieldset;
}
/*
use this to create the initial bindings rather than jQuery
the reason? I find .live() to be buggy. it doesn't always work. this usually means having to use a standard .bind()
and then re-bind when we add in the new set
that's what this class helps with. when it adds in the new data, it rebinds for you. nice and easy.
*/
AddMore.prototype.bind = function(type, $button)
{
if (!type || !$button && (type != 'add' && type != 'remove'))
throw 'Invalid paramaters';
// don't reapply the bindings to old elements...
if ($button.hasClass('addmore-binded'))
return;
// jQuery overwrites 'this' within it's scope
var _this = this;
if (type == 'add')
{
$button.bind('click', function()
{
_this.element.after(_this.cache);
});
}
}
在添加新的字段集以重新应用绑定时,我打算在自己的类中调用.bind()方法,但对效率(速度/内存)失去信心。
我该如何解决? 你有指针吗? 您能建议改进吗?
谢谢您的帮助。
以最简单的形式,您可以执行以下操作:
var html = '{put html to add each time here}';
$('.add').click(function() {
$(html).insertAfter($('fieldset').last());
return false;
});
$('.remove').live('click', function() {
$(this).parent().remove();
return false;
});
您可能需要根据实际需求进行调整,但这应该可以完成您在示例中描述的内容。
更新:抱歉,删除应使用实时方法。
为了创建新的DOM元素,允许规范/参数为以下任意一项:
选项#1似乎几乎没有用,但是#3可能很难,除非您现在有多余的时间。
笔记:
$(theNewDomElement).insertBefore(_this.button);
而不是_this.element.after(theNewDomElement);
以便将新项目添加到列表的末尾 。 this
而不是_this.button
因为大概按钮(或锚点) 是 this
,但是那限制了功能-使其成为某种DOM元素(或等同于jQuery对象)一)。 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.