JQuery数据属性选择器未定义

bis*_*ack 1 html javascript css jquery

我在一些基本的html和javascript中遇到数据属性问题.我在整个页面中有几个链接,可动态插入地图和"关闭"链接以摆脱地图.

这些链接都类似于:

<a class="maplocation" href="#" data-coords="4645/234234" data-zoom="9">Link text<span class="mapslideicon"></span></a>
Run Code Online (Sandbox Code Playgroud)

点击这些链接的javascript是:

$("a.maplocation").click(function() {
    if ($(this).data("mapopen") == true) {
        // Map already clicked and open, do nothing
    } else {
        var timeStamp = $.now();
        var mapID = "m_"+timeStamp;
        var mapCloseID = "c_"+timeStamp;
        var anchorID = "a_"+timeStamp;
        var mapClass = 'widemap';
        var mapDiv = $("<div class='"+mapClass+"' id='"+mapID+"'>&nbsp;</div><a href='#' id='"+mapCloseID+"' class='maplocationclose'>close</a>");
            mapDiv.insertAfter($(this).parent());
        // Set a data attribute on the link to let it know a map is open
        $(this).data( "mapopen", true );
        // Set a data attribute on the link so that we can reference it from the close button
        $(this).data( "anchorid", anchorID );
    }
    return false;
});
Run Code Online (Sandbox Code Playgroud)

这会为地图创建一个div,在原始锚点上放置一个数据属性以表示地图已打开,并且还会创建一个用于关闭地图的锚点.

单击关闭贴图锚点时,它将执行以下操作:

$('body').on('click', 'a.maplocationclose', function(){ // delegated.
        var id = $(this).attr('id');
        idNo = id.split("_");
        var assocMapID = "m_"+idNo[1];
        var assocAnchorID = "a_"+idNo[1];
        $("#"+id).remove();
        $("#"+assocMapID).slideUp( 300, function() {
            $("#"+assocMapID).remove();
        });
    // Set a data elemt on the original map link that let's us know the map is closed again
    $('.maplocation[anchorid="'+assocAnchorID+'"]').data( "mapopen", false );
    return false;
});
Run Code Online (Sandbox Code Playgroud)

这一切都有效,但我很难从关闭锚点访问数据属性.如我所愿,它从原始链接引用精细,并将映射属性设置为true并将其读为true.但是,当我在关闭锚点中将其设置为false时,它无法找到它并且它永远不会被设置.

我已经运行了一个测试(从maplocationclose函数内部)来查看我是否可以从锚点找到任何数据属性,例如:

console.log("Zoom Attr is: " + $('a.maplocation[anchorid="'+assocAnchorID+'"]').data('zoom'));
Run Code Online (Sandbox Code Playgroud)

他们正在回归'未定义'.

Geo*_*rge 5

使用附加数据.data()不会添加/更改任何data-*属性,因此您的属性选择器将不匹配任何内容.

您可以使用过滤器代替:

$('.maplocation').filter(function(){
    return $(this).data('anchorid') == assocAnchorID;
}).data( "mapopen", false );
Run Code Online (Sandbox Code Playgroud)