我正在从array
对象呈现动态输入和复选框,这很好,但我不太确定当我点击{input
时如何隐藏checkbox
{1}}相对于输入。
function dynamicStuff () {
var objs = ['Id', 'Name', 'Age'];
for (var i = 0; i < objs.length; i++) {
objs[i];
var cElement = document.createElement("input");
cElement.type = "checkbox";
cElement.name = objs[i];
cElement.id = objs[i];
var cElementInput = document.createElement("input");
cElementInput.type = "text";
cElementInput.name = objs[i];
cElementInput.id = objs[i];
cElementInput.placeholder = objs[i]
document.getElementById('chkBox').appendChild(cElement);
document.getElementById('chkBox').appendChild(cElementInput);
}
}
在localStroage上保存:
function chkboxCookie() {
var indexOfItem = checkAllFields.indexOf(this.id);
if (indexOfItem >= 0) {
checkAllFields.splice(indexOfItem, 1);
} else {
checkAllFields.push(this.id);
}
/* it saves paramater name in the localStorage*/
localStorage.setItem("checkedUsers", JSON.stringify(checkAllFields));
}
如何隐藏我勾选的input
并可能在localStorage中保存input
名称/ ID?
答案 0 :(得分:1)
<强> Working fiddle 强>
id
属性在同一页面中应该是唯一的,因此请尝试更改输入的ID,例如:
cElementInput.id = objs[i]+'_input';
并将更改事件附加到您将显示/隐藏相关输入的复选框:
cElement.addEventListener("change", toggleInput, false);
然后定义您的toggleInput()
功能:
function toggleInput(){
var input_id = this.id+'_input';
document.getElementById(input_id).style.display = this.checked ? 'inline' : 'none';
localStorage.setItem(this.id, this.value);
}
要check/uncheck
基于localStorage
的复选框,请先获取数据:
var localStorageData = JSON.parse(localStorage.getItem("checkedUsers"));
var data = localStorageData==null?[]:localStorageData;
然后检查数组中显示的值和check/uncheck
复选框:
if(data.indexOf(objs[i]) >= 0)
cElement.checked = true;
else
cElement.checked = false;
希望这有帮助。
答案 1 :(得分:1)
当选中复选框时,您将添加一个对输入执行某些操作的事件处理程序
function dynamicStuff() {
var objs = ['Id', 'Name', 'Age'];
for (var j = 0; j < objs.length; j++) {
(function(i) {
objs[i];
var cElementInput = document.createElement("input");
cElementInput.type = "text";
cElementInput.name = objs[i];
cElementInput.id = objs[i];
cElementInput.placeholder = objs[i];
var cElement = document.createElement("input");
cElement.type = "checkbox";
cElement.name = objs[i];
cElement.id = objs[i];
cElement.addEventListener('change', function() {
cElementInput.style.display = this.checked ? 'none' : 'inline';
localStorage.setItem(objs[i], this.value);
});
var br = document.createElement('br');
document.getElementById('chkBox').appendChild(cElement);
document.getElementById('chkBox').appendChild(cElementInput);
document.getElementById('chkBox').appendChild(br);
document.getElementById('chkBox').appendChild(br.cloneNode());
})(j);
}
}
dynamicStuff()
<div id="chkBox"></div>