我有一个很棒的工作功能,可以检查是否有人点击了我页面上的复选框并做了很多事情。容纳复选框的容器旁边还有一个缩略图图像,我想试着找出一种方法,我可以模仿我单击图像时单击实际复选框时使用的相同功能。它应该与复选框切换相同,选择它并执行它现在执行的所有其他操作:
这是我当前的复选框点击功能的jquery代码:
// Checkbox Actions - If a Checkbox is checked or not
$(":checkbox").click(function() {
var checkedState = $(this).is(':checked');
var product = $(this).attr("name");
var newName = '.' + product ;
var productImg = '.' + product + '-img';
// Check List Count and Show/Hide Sections
var currentCount = countChecked();
if (currentCount == 0) {
$(newName).css("display", "none");
$("#noProducts").delay(1).fadeIn(350);
$("#listContainer").removeClass("listContainerProducts");
$("#haveProducts").css("display", "none");
checkIfScrollable();
}
// Hide the No Products Container if List Count is Greated than 0
if (currentCount > 0) {
$("#noProducts").css("display", "none");
$("#haveProducts").css("display", "");
checkIfScrollable();
}
// Check the checkbox state and select/show correct items in the List if selected
if (checkedState == true) {
var productName = $(this).attr("title");
var productClassName = $(this).attr("name");
$("#selectedProductsList").append("<li class=\"productList " + productClassName + "\"><p class=\"removeIcon\"><img src=\"images/remove-icon.png\" alt=\"Remove Product\" /></p><span class=\"productName\">"+ productName +"</span></li>");
$(".listBoxContainer").fadeIn(350);
// Change the Image Wrapper to be Selected if checked - Green Border
$(productImg).addClass("imageBoxTopSelected");
$("#listContainer").addClass("listContainerProducts");
$(newName).css("background", "#FFFFFF");
}
// If checkbox is not checked
if (checkedState == false) {
$(newName).fadeOut(500, function() { $(this).remove()});
$(productImg).removeClass("imageBoxTopSelected");
checkIfScrollable();
}
});
我知道我的jquery不是简化(jquery nobe),但它做了我需要的。
只需要找出一种模仿复选框的方法,点击图片即可。
有什么想法吗?感谢
答案 0 :(得分:1)
我并不完全确定你要求的是什么。您是否只是想在单击图像时触发复选框上的clik事件?
$("#mythumb").click(function(){
// well here the selector is certainly too big, you need to get only
// the related checkbox. Maybe you could store a rel="checkboxid" attribute on
// the thumb and get it with:
// var checkid=$(this).attr("rel");
// or find th checkbox in the DOM near you image with stuff like
// var mychk = $(":checkbox",$(this).parent('div'));
$(":checkbox").trigger('click');
// or
$(":checkbox").click();
};
编辑:新尝试(并重新编辑,因为我忘记使用triggerHandler而不是触发器 - 以及语法错误):
$("#mythumb").click(function(){
var mychk = $(":checkbox",$(this).parent('div'));
// toggle checked attribute
mychk.attr('checked', !mychk.is(":checked"));
// trigger the click event without effectively clicking.
// this way the behaviour is the same in old IE and FF
mychk.triggerHandler('click');
});