2016-12-30 93 views
4

得到inputName我有一个动态的input这将有checkbox隐藏输入时,你打勾的checkbox,此刻我想补充click="getChk()checkbox但它只是给我最后的index inputName。上复选框添加动态点击jQuery的

说我输入了Ids(代码,sku,id)。

我的动态输入和检查代码行是

for (var x = 0; x < searchParams.length; x++) { 
    var container = $('#checkBox'); 
    var inputs = container.find('input'); 
    var id = inputs.length + 1; 
    var inputName = searchParams[x].name; 
    $('<textarea />', { id: inputName, name: inputName, placeholder: inputName, rows: "2", class: "search-area-txt col-sm-12" }).appendTo(searchbox); 
    $('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox); 
    $('<label />', { 'for': 'x' + id, text: inputName, id: inputName, name: inputName }).appendTo(checkBox); 
} 

但是,这将需要的时候刷新它会持续输入被隐藏其在localStorage存在时,被保存在localStorage左右。

编辑:下面的代码应在localStorage保存名称以阵列形式。

var inputNames = []; 
getChk(id){ 
var indexOfItem = inputNames.indexOf(name) 
if (indexOfItem >= 0) { 
    inputNames.splice(indexOfItem, 1); 
} else { 
    inputNames.push(name); 
} 
localStorage.setItem('chked', JSON.stringify(inputNames)) 
} 

我的尝试是通过增加.click(function(){})

$('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox).click(function(){ 
getChk(id); // only gives me the id name 
}); 

HTML输入框的HTML enter image description here

回答

3

的问题是因为当click事件处理程序运行for循环已完成,因此id变量保存最后一个值。

为了解决这个问题,修改你的点击处理程序,直接从引发事件的元素读取id属性:

$('<input />', { type: 'checkbox', id: 'x' + id, name: inputName }).appendTo(checkBox).click(function() { 
    getChk(this.id); 
}); 

此外,如发现由@ guest271314,设置localStorage时正确的方法数据setItem() ,不set()

localStorage.setItem('checked', id); 
+0

@ guest271314谢谢 - 很好发现 –

+1

对不起,我的意思是说'.setItem',哦对了会尝试添加'this' – MrNew

+0

,但是我怎样才能把'checkbox'对应到'textarea',只是认为'this .id'只会给我'复选框'的id而不是'textarea' – MrNew

0

你可以试试下面的代码

getChk(e){ 
localStorage.set('checked', this.id); 
console.log('input id>> ', this.id); 
} 

.click(getChk);