第一次点击toggleclass()
时没有添加选定的课程,但之后会顺利进行
HTML:
<li class="categories col-lg-3 col-md-3 col-sm-4 col-xs-4 text-center pb20 pointer" id="1" onclick="categories(this.id)">
<img src="some-image" class="registerCategory">
Rice
</li>
JS:
var taken1 = [];
function categories(c_id) {
$("li.categories").click(function(e1) {
e1.preventDefault();
$(this).toggleClass("selected");
e1.stopImmediatePropagation();
});
var inp = document.getElementById("categories");
var ind = taken1.indexOf(c_id);
if(ind > -1){
taken1.splice(ind,1);
taken1 = taken1;
} else {
taken1.push(c_id);
}
inp.value = taken1.join(',');
}
答案 0 :(得分:1)
当您在click
处理程序中附加事件处理程序时出现问题。
在函数categories()
$("li.categories").click(function (e1) {
e1.preventDefault();
$(this).toggleClass("selected");
e1.stopImmediatePropagation();
});
function categories(c_id) {
//relevant code
}
但是,当您绑定事件时,请删除内联单击处理程序并删除onclick="categories(this.id)"
<li class="categories col-lg-3 col-md-3 col-sm-4 col-xs-4 text-center pb20 pointer" id="1" ><img src="some-image" class="registerCategory">Rice</li>
脚本
$("li.categories").click(function (e1) {
e1.preventDefault();
$(this).toggleClass("selected");
e1.stopImmediatePropagation();
//Call the function from event handler
categories(this.id);
});
答案 1 :(得分:0)
您的活动在首次点击后绑定。在您的功能之外绑定click
事件。
var taken1 = [];
$("li.categories").click(function(e1) {
e1.preventDefault();
$(this).toggleClass("selected");
e1.stopImmediatePropagation();
});
function categories(c_id) {
var inp = document.getElementById("categories");
var ind = taken1.indexOf(c_id);
if(ind > -1){
taken1.splice(ind,1);
taken1 = taken1;
} else {
taken1.push(c_id);
}
inp.value = taken1.join(',');
}
&#13;
.selected { background-color: #7bf29f; border-radius: 50%; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="categories col-lg-3 col-md-3 col-sm-4 col-xs-4 text-center pb20 pointer" id="1"><img src="some-image" class="registerCategory">Rice</li>
&#13;