我在jQuery中的一系列开/关开关有问题.
这是交换机的标记:
<div class="switchOnOff"> <div class="switchLed"></div> <p class="switchFeedback"></p> <a class="switchButton" rel="on" id="one"><span></span></a> </div> <div class="switchOnOff"> <div class="switchLed"></div> <p class="switchFeedback"></p> <a class="switchButton" rel="on" id="two"><span></span></a> </div>
这是我的js:
$('.switchOnOff .switchButton').click(function() { if ( $('.switchButton').attr('rel') == 'off' ) { $(this).next('.switchLed').addClass("on"); $(this).prev('.switchFeedback').html("on"); } else if ( $('.switchButton').attr('rel') == 'on' ) { $(this).next('.switchLed').addClass("off"); $(this).prev('.switchFeedback').html(FeedbackOn); }});
但是这段代码不起作用.我也尝试使用“next”,“prev”或“最接近”的选择器,但DOM遍历不起作用.
总之,我希望获得一个可以改变单个开关状态的开/关功能.
我希望我很清楚.
任何帮助都会得到充分的帮助.
解决方法
你可以做(评论后更新)
$('.switchOnOff .switchButton').click(function() { var div = $(this).closest('.switchOnOff'); var $this = $(this); if ($this.attr('rel') == 'off') { $this.attr('rel','on'); div.find('.switchLed').addClass("on").removeClass("off"); div.find('.switchFeedback').html("on"); } else if ($this.attr('rel') == 'on') { $this.attr('rel','off'); div.find('.switchLed').addClass("off").removeClass("on"); div.find('.switchFeedback').html("off"); } });
在这里摆弄http://jsfiddle.net/YpfmD/3/
编辑最后评论:设置你可以做的“第一关”:
var switcher = function(el) { var div = $(el).closest('.switchOnOff'); var $this = $(el); if ($this.attr('rel') == 'off') { $this.attr('rel','on'); div.find('switchLed').addClass("on").removeClass("off"); div.find('.switchFeedback').html("on"); } else if ($this.attr('rel') == 'on') { $this.attr('rel','off'); div.find('switchLed').addClass("off").removeClass("on"); div.find('.switchFeedback').html("off"); } }; //Set up the varIoUs div $('.switchOnOff .switchButton').each(function() { switcher(this); }); //attach the handler $('.switchOnOff .switchButton').click(function() { switcher(this); });