У меня есть список li в ul с классом "color-boxes". Каждый из них li имеет атрибут данных "data-color". Эти атрибуты данных также находятся в совпадающих изображениях, соответствующих каждому элементу li. То, что я пытаюсь сделать, это получить каждый образ, который идет с каждым li, который будет заменен, когда вы наводите курсор мыши или нажимаете на li с соответствующим атрибутом данных. Вот мой текущий jquery. Пожалуйста, имейте в виду, я не знаю, что я делаю, когда дело доходит до jQuery:
jQuery (document).ready(function() {//для каждого ul.color-boxes li
jQuery("ul.color-boxes li").each(function() {
// bind click event
jQuery(this).bind('click', function() {
jQuery("li").attr("data-color");
});
});
jQuery("figure.main-image img").each(function() {
jQuery("img").attr("data-color");
});
//ul.color-boxes li === figure.main-image img
function showImg(strShow, strHide)
{
// hide all figure.main-image img
jQuery("figure.main-image img[data-color='"+ strShow +"']").show();
document.getElementById(strShow).style.display = 'block';
document.getElementById(strHide).style.display = 'none';
}
});
У кого-нибудь есть помощь, которую они могут отправить?
Я думаю, что это решение, которое вы ищете:
jQuery(document).ready(function() {
jQuery("ul.color-boxes li").on("click", function() { // foreach each ul.color-boxes li
var sColorVal = jQuery(this).attr("data-color");
if (typeof(sColorVal) != "undefined") {
jQuery("figure.main-image img[data-color='"+ sColorVal +"']").show(); // show images with clicked "data-color" value
jQuery("figure.main-image img[data-color!='"+ sColorVal +"']").hide(); // hide images with deffrent "data-color" value
}
});
});
on("click hover", function() { ... })
. Или вы можете прикрепить еще одно событие: on("click", function() { ... }).on("hover", function() { ... })
Я немного модифицировал ваш код, а также пытался добавлять комментарии, если это необходимо, надеюсь, достаточно;)
jQuery(document).ready(function(){
var strShow="";
var strHide="";
function showImg()
{
// if a image is already visible and if it is not the same image as the image that is to be made visible
if(strHide.length>0 && strShow!=strHide){
// hide previous figure.main-image img
jQuery("figure.main-image img[data-color='"+ strHide+"']").hide();
}
jQuery("figure.main-image img[data-color='"+ strShow +"']").show();
//Keeping track of the currently visible image to hide later if required
strHide=strShow;
}
jQuery("ul.color-boxes li").each(function() {
// bind click event
jQuery(this).bind('click', function() {
//getting the data-color to associate with the current image to show
strShow=jQuery(this).attr("data-color");
//calling the function to show the current image
showImg();
});
});
});