从jquery中的属性开始,在遍历dom的系列中更改单个开/关开关的状态

我在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);
});

在这里小提琴:http://jsfiddle.net/YpfmD/4/

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...