如果选中了复选框,我将尝试将一些对象添加到数组中。但我似乎无法让它发挥作用。我想要的是根据选中的复选框的值添加一个对象。我希望你们能够理解。让我用代码向您展示:
这是检查复选框是否被选中的代码:
var filter_options=[];
$('input:checkbox').click(function()
{
var name=$(this).val().trim();
if(this.checked)
{
filter_options.push(name);
console.log('Add: ' + name);
}
else
{
var index=filter_options.indexOf(name);
if(index > -1)
{
filter_options.splice(index, 1);
console.log('Remove: ' + name + ' at index: ' + index);
}
}
$('#result').html(filter_options.join('; '));
console.log(filter_options);
});
让我们这些是对象:
var human = new Human();
var dog = new Dog();
var cat = new Cat();
var options = []; //push the objects here depending on the checkboxes value.
这是我的 html :
<div class="option">
<input type="checkbox" value="human">
<input type="checkbox" value="dog">
<input type="checkbox" value="cat">
</div>
如何根据复选框值将这些对象添加到数组中?任何帮助将不胜感激。
最佳答案
function Human() {
this.id = 1;
this.firstName = "Human";
this.lastName = "Last Name";
this.age = 5;
this.eyeColor = "color";
}
function Dog() {
this.id = 2;
this.firstName = "Dog";
this.lastName = "Last Name";
this.age = 5;
this.eyeColor = "color";
}
function Cat() {
this.id = 3;
this.firstName = "Cat";
this.lastName = "Last Name";
this.age = 5;
this.eyeColor = "color";
}
var human = new Human();
var dog = new Dog();
var cat = new Cat();
var filter_options=[];
$('input:checkbox').click(function()
{
var id = $(this).attr("data-id");
var name=$(this).val().trim();
if(this.checked)
{
if(id==1){
filter_options.push(human);
}
else if(id==2){
filter_options.push(dog);
}
else if(id==3){
filter_options.push(cat);
}
}
else
{
var index=filter_options.indexOf(name);
if(index > -1)
{
filter_options.splice(index, 1);
console.log('Remove: ' + name + ' at index: ' + index);
}
for(var i = 0; i < filter_options.length; i++) {
if(filter_options[i].id == id) {
filter_options.splice(i, 1);
break;
}
}
}
$('#result').html(filter_options.join('; '));
console.log(filter_options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="option">
<input type="checkbox" value="human" data-id="1">
<input type="checkbox" value="dog" data-id="2">
<input type="checkbox" value="cat" data-id="3">
</div>
关于javascript - 如果选中复选框,则将对象添加到数组,如果未选中,则将对象删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49230217/