从jQuery方法返回值

时间:2013-05-10 12:57:03

标签: jquery methods return-value

我从插件Megalist调用方法getSelectedIndex,如下所示:

var selectedIndex = $('#left-list').megalist('getSelectedIndex');

但是,我得到一个代表该列表的jQuery对象,而不是返回一个整数。我试图直接调用该方法,两者都是

var selectedIndex = $('#left-list').getSelectedIndex();

var selectedIndex = $('#left-list').megalist().getSelectedIndex();

然后我收到一条错误,指出没有名为getSelectedIndex的方法。插入.eq(0)以仅隔离第一个jQuery对象也不起作用。我尝试使用谷歌搜索,但these few pages似乎没有提供答案。该方法定义如下:

getSelectedIndex: function() {
    return parseInt(this.selectedIndex, 10);
},

并且应该返回一个整数。我怎样才能调用该方法来返回一个整数呢?

更新:似乎做了这样的事情:

window.selectedIndex = -1;
// ...
function listChangeHandler( event ) { 
    // ...
    window.selectedIndex = event.selectedIndex;
    // ...
}

// ...

$('.favorite-link').on('click', function(){
    if (window.selectedIndex != -1)
    {
        if (window.favorites.indexOf(window.selectedIndex) == -1)
        {
            window.favorites.push(window.selectedIndex);
        }
    }
});

可以解决问题,但我仍然想知道是否可以在不使用全局变量的情况下完成此操作。

2 个答案:

答案 0 :(得分:1)

初始化插件时,未选择任何项目。只需将change处理程序绑定到#left-list,您就可以从selectedIndex对象获取event

$('#left-list').on('change', function(e) {
  var selectedIndex = e.selectedIndex;
});

<强> Check the documentation

答案 1 :(得分:1)

当选择了megalist中的项目时,类.megalistSelected被添加到列表项中,因此您可以使用jQuery搜索该类的<li>并获取其list-index的值。 1}}属性。

以下面的megalist标记为例:

   <div class="megalist" id="myList2">
         <ul style="visibility: visible; left: 0px; top: 0px;">
            <li class="megalistItem megalistSelected" list-index="1" style="left: 0px; top: 41px;">Decimal: 1, Hex: 1</li>
         </ul>
   </div>

则...

$('#myList2').find('.megalistSelected').attr('list-index')

...将检索项目的索引(当然,一旦选择了项目)。