如何查询DOM以获取具有事件“sortremove”的属性值

时间:2014-01-05 19:05:52

标签: jquery jquery-ui jquery-ui-sortable

当“赞助商”从一个团队拖到另一个团队时,我需要运行一个ajax请求来删除数据库中的赞助商。

<ul class="teamList clearAfter">
        <li class="team" data-teamid="548">
            <label>Team 1</label>
            <div class="edit"></div>
            <div class="delete"></div>
            <ul class="sponsors ui-sortable">
                    <li data-sponsorname="Katie E.">Katie E.</li>
                    <li data-sponsorname="Rachel R.">Rachel R.</li>
            </ul>
            <ul class="players ui-sortable">
                    <li class="grade-9" data-playerid="86"><label>Abby M.</label></li>
            </ul>
        </li>
        <li class="team" data-teamid="557">
            <label>Team 2</label>
            <div class="edit"></div>
            <div class="delete"></div>
            <ul class="sponsors ui-sortable">
                    <li data-sponsorname="Danielle M.">Danielle M.</li>
                    <li data-sponsorname="David J.">David J.</li>
                    <li data-sponsorname="Jeff Wilson">Jeff Wilson</li>
            </ul>
            <ul class="players ui-sortable">
                    <li class="grade-12" data-playerid="91"><label>Scottie B.</label></li>
                    <li class="grade-10" data-playerid="78"><label>Nathan P.</label></li>
            </ul>
        </li>
    </ul>

我正在使用jQuery UI的sortremove事件。问题似乎是在删除项目后发生了对DOM的查询。

$('#teams .sponsors').bind('sortremove', function (e, ui) {
    console.log(ui.item[0]);
    console.log($(ui.item[0]).closest('.team')); //not found
    console.log($(ui.item[0]).closest('.team').attr('data-teamId'));
    $.ajax({
        type: 'post',
        url: '/api/team/removeSponsor/',
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify({
            teamId: $(ui.item[0]).closest('.team').attr('data-teamId'),
            sponsor: $(ui.item[0]).attr('data-sponsorName')
        })
    });
});

1 个答案:

答案 0 :(得分:1)

您将不得不使用sortreceive事件,从而获得对ui.sender属性的访问权限,该属性包含传入可排序的列表。

$('.sponsors').bind('sortreceive', function (e, ui) {
    var sender = ui.sender,
        teamId = sender.closest('.team').data('teamid'),
        sponsor = $(ui.item[0]).data('sponsorname');

    console.log(sender, teamId, sponsor);

    $.ajax({
        type: 'post',
        url: '/api/team/removeSponsor/',
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify({
            teamId: teamId,
            sponsor: sponsor
        })
    });
});

演示 http://jsfiddle.net/f9B8P/