我想在脚本上再次获取索引

时间:2013-07-30 05:52:06

标签: jquery

我想再次检查索引值。但是对我来说,我的代码只能创建一次

$(function() {
    $('.tree').on("click", 'a',function(e) {
        var top = $(this).closest('tr').index()
        var cont = $(this).closest('tr').html()
      //  alert(cont)
        if ( top === 1) {
            alert('it is top')
            return false
            top = $(this).index()
        } else {
            $(this).closest('tr').empty()
            $('.second').before('<tr class="tree">'+ cont + '</tr>')
            top = $(this).index()
        }
    })
})

我把代码放在jsfiddle上:http://jsfiddle.net/Jackyhua/gjypb/ 也许我需要“为”才能使它发挥作用。

2 个答案:

答案 0 :(得分:0)

$(function() {
    $('.tree').on("click", 'a',function(e) {
        var top = $(this).closest('tr').index()
        var cont = $(this).closest('tr').html()
      //  alert(cont)
        if ( top === 1) {
            alert('it is top')
            top = $(this).index()
            return false // you were returning before the index() stmt
        } else {
            $(this).closest('tr').empty()
            $('.second').before('<tr class="tree">'+ cont + '</tr>')
            top = $(this).index()
        }
    })
})

但你可能需要的是

$(function() {
    $('table').on("click", 'a',function(e) {
        var tr = $(this).closest('tr'), table = tr.closest('table');
        tr.insertBefore(table.find('tr').eq(1));
        return false;
    })
})

演示:Fiddle

答案 1 :(得分:0)

使用此:

<强> FIDDLE

$(function() {
        $('table').on("click", '.tree a',function(e) {
            var top = $(this).closest('tr').index()
            var cont = $(this).closest('tr').html()
          //  alert(cont)
            console.log(top);
            if ( top === 1) {
                alert('it is top')
                return false
            } else {
                $(this).closest('tr').empty()
                $('.second').before('<tr class="tree">'+ cont + '</tr>')
            }
        })
})

问题是您在dom之后删除并添加tr。通过使用未更改的元素,您可以(使用.on())再次定位.tree