我在一些基本的 html 和 javascript 中遇到数据属性问题。我在一个页面中有几个链接,动态插入 map 和一个“关闭”链接以删除 map 。
链接都类似于:
<a class="maplocation" href="#" data-coords="4645/234234" data-zoom="9">Link text<span class="mapslideicon"></span></a>
点击这些链接的 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+"'> </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;
});
这会为 map 创建一个 div,在原始 anchor 上放置一个数据属性以表明 map 是打开的,并且还会创建一个用于关闭 map 的 anchor 。
单击关闭 map anchor 时,它会执行以下操作:
$('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;
});
这一切都有效,但我很难从关闭的 anchor 访问数据属性。如我所愿,它从原始链接中引用得很好,并将映射属性设置为 true 并将其读取为 true。但是,当我在关闭 anchor 中将其设置为 false 时,它找不到它并且从未设置过。
我已经运行了一个测试(从 maplocationclose 函数内部)以查看我是否可以从 anchor 找到任何数据属性,例如:
console.log("Zoom Attr is: " + $('a.maplocation[anchorid="'+assocAnchorID+'"]').data('zoom'));
他们返回“undefined”。
最佳答案
使用 .data()
附加数据不会添加/更改任何 data-*
属性,因此您的属性选择器不会匹配任何内容。
您可以改用过滤器:
$('.maplocation').filter(function(){
return $(this).data('anchorid') == assocAnchorID;
}).data( "mapopen", false );
关于javascript - JQuery 数据属性选择器未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31185652/