简体   繁体   English

如何通过事件增加/减少对象的属性值?

[英]How to increment/decrement an objects property value with an event?

Im trying to use the accordion widget for jQuery-ui. 我正在尝试将手风琴小部件用于jQuery-ui。 What i am trying to build is a function that will cycle through all the tabs with a swipe. 我正在尝试构建的功能是通过滑动在所有选项卡之间循环。 For the sake of this example i am using a click event since i have the swipe up/down event listener working separately and is off topic from my question. 对于此示例,我使用了click事件,因为我具有向上/向下滑动事件监听器,它们分别工作并且与我的问题无关。 Essentially a user will swipe or click an area and the tabs will cycle the 3 sections back and forth. 本质上,用户将滑动或单击一个区域,而选项卡将使这三个部分来回循环。

Am i on the right track or is there a better way to accomplish this? 我是在正确的轨道上吗,还是有更好的方法来做到这一点?

jsFiddle demo jsFiddle演示

JS JS

$(function () {
    $("#accordion").accordion({
        collapsible: true,
        active: false
    });
});


$('#cycle').click(function () {

    $('#accordion').accordion({
        active: 0
    });

    function incrementAccValue(obj, val) {
        obj = $('#accordion').accordion({
            active: val
        });

        obj.active++ //stuck here..?

    }

});

//How to increment an object's property value?

You are on the right track. 您走在正确的轨道上。 You just need to store the active number outside of the scope of the click function so that the value will be available on the next click event. 您只需要将有效数字存储在click函数范围之外,以便该值将在下一次click事件中可用。

Something like this should work: http://jsfiddle.net/30vm5y75/ 这样的事情应该起作用: http : //jsfiddle.net/30vm5y75/

var max_items = $('#accordion h3').length;
var current_item = 0;

$('#cycle').click(function () {

    $('#accordion').accordion({
        active: current_item
    });

    if (current_item < max_items-1) {
        current_item = current_item + 1;
    } else {
         current_item = 0;   
    }

});

Not sure if this is what you need, but I have updated your fiddle here . 不知道这是否是您所需要的,但是我在这里更新了您的小提琴。

Updated JS: 更新的JS:

var activeIndex = 0,
    maxIndex = $("#accordion h3").length - 1;

$(function () {
    $("#accordion").accordion({
        collapsible: true,
        active: false
    });
});

$('#cycle').click(function () {

    $('#accordion').accordion({
        active: activeIndex
    });

    activeIndex = ( activeIndex == maxIndex ? 0 : activeIndex+1);

});   

From the doc: 从文档中:

// Getter
var active = $( ".selector" ).accordion("option", "active" );

// Setter
$( ".selector" ).accordion( "option", "active", 2);

So, you don't have to store the current index anywhere; 因此,您不必将当前索引存储在任何地方。 just get the active index, then set the active index to active + 1 or the length of the accordion minus one, whichever is smaller. 只需获取活动索引,然后将活动索引设置为active + 1或手风琴的长度减去一(以较小者为准)即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM