それで、しばらく退屈しました。というわけで、これを提供してもよろしいでしょうか?
var startValues = ['apple', 'banana', 'cherry'];
function childElementType(node) {
var props = {
childType: '',
textType: Node.textContent ? 'textContent' : 'innerText',
hasValue: false
};
switch (node.tagName.toLowerCase()) {
case 'select':
props.childType = 'option';
props.hasValue = true;
break;
case 'ol':
case 'ul':
props.childType = 'li';
break;
}
return props;
}
Object.prototype.populate = function (values) {
if (this.length) {
return this;
} else {
var child = childElementType(this),
newChild;
for (var i = 0, len = values.length; i < len; i++) {
newChild = document.createElement(child.childType);
newChild[child.textType] = values[i];
if (child.hasValue) {
newChild.value = newChild[child.textType];
}
this.appendChild(newChild);
}
}
return this;
};
Object.prototype.addTo = function (message) {
var control = document.createElement('button'),
that = this;
control.appendChild(document.createTextNode(message || '+ add to ' + that.tagName.toLowerCase()));
this.parentNode.insertBefore(control, this.nextSibling);
var child = childElementType(this);
function addNew() {
var text = prompt('Add the new entry:'),
newEntry;
if (text) {
newEntry = document.createElement(child.childType);
newEntry[child.textType] = text;
that.appendChild(newEntry);
}
}
control.onclick = addNew;
return this;
};
document.getElementById('select').populate(startValues).addTo();
document.getElementById('ul').populate(startValues).addTo();
JS フィドルのデモ。
メソッドにデフォルトのメッセージをaddTo()
渡して、作成したボタンに特定のテキストを与えることもできます。各メソッドはオブジェクト/ノードを返すため、どちらの順序でも呼び出すことができます (もちろん、最初this
に要素を選択する限り)。)、たとえば、これらのアプローチは両方とも有効で使用可能です。
document.getElementById('select').addTo('Moar options..?').populate(startValues);
document.getElementById('ul').populate(startValues).addTo('Go on, add more!');
JS フィドルのデモ。
参考文献: