我一整天都在努力解决这个问题。我将给你一个我一直在尝试做的事情的简化摘要。用户输入一个数字,无论这个数字有多大,都是下一页上的类别数量。在每个类别中,都有一个输入文本按钮,以及一个动态添加其他输入文本框的"添加文本框"按钮。然而,这里的问题是,每个类别在同一页面上都有相同的设置。例如,如果用户输入数字"3",则页面将垂直加载三个类别,如下所示:
Category #1
(Initial user input textbox for category #1)
("Add Textbox" button to allow user to fill out another option)
Category #2
(Initial user input textbox for category #2)
("Add Textbox" button to allow user to fill out another option)
Category #3
(Initial user input textbox for category #3)
("Add Textbox" button to allow user to fill out another option)
我遇到的困难是,每个类别按钮都需要有自己的功能,告诉按钮将文本框放在哪里。再加上类别的数量根据用户的输入而变化,这让事情变得很困难。我从以下内容开始:
var categoryCount = <?php echo $categoryCount; ?>;
var click = {};
for (var num=1;num<=categoryCount;num++) {
var newClick = "click_" + num;
click[newClick] = function() {
// some contents when this button is clicked
};
}
这个JS创建了一个函数对象,在JS中可以通过执行以下操作来访问它:
click['click_' + someID]();
然而,问题是,我不能使用HTML/PHP按钮中的"onclick"属性来实现这一点。显然,我不能访问这个函数对象,也不能调用任何单独的函数。我想我需要重新思考这一切,重新开始。我只是想不出其他方法来让它发挥作用。请和我分享你的想法!非常感谢您的帮助。
对于这样的东西,我会写一个可以像一样使用的构造函数
var cat1 = new Category(document.body);
幸运的是,我也写了一个例子。请参阅此处演示。不过,我根本没有为新的线条等设计它。
var Category = (function () {
var categoryCount = 0;
function elem(tag) { // shortcut
return document.createElement(tag);
}
function text(str) { // shortcut
return document.createTextNode(str);
}
function Category(node) {
var self = this; // this should have been var'd, oops!!
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.append(node);
}
}
Category.prototype.addTextbox = function () {
var e = elem('textarea');
e.setAttribute('name', 'cat-'+this.categoryId+'-textbox[]');
this.textboxes.push(e);
this.wrapper.insertBefore(e, this.addButton);
};
Category.prototype.append = function (node) {
return node.appendChild(this.wrapper);
};
return Category;
}());