微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从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/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐