0

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

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

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

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

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

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

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

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

4

2 回答 2

1

When an item in the megalist has been selected, the class .megalistSelectedis added to the list item so you could search for a <li>with that class using jQuery and get the value of its list-indexattribute.

以下面的 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')

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

于 2013-05-10T14:13:41.643 回答
1

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

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

检查文档

于 2013-05-10T13:24:02.000 回答