我遇到了一些基本的html和javascript中的数据属性问题。我在整个页面中有几个链接,可以动态插入地图和“关闭”链接以摆脱地图。JQuery数据属性选择器undefined
的链接都是相似的:
<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;
});
这对地图创建一个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;
});
这一切工作,但我有从接近锚访问数据属性的难度。按照我的意图,它从原始链接中引用良好,并将映射属性设置为true并将其读取为true。但是,当我在关闭锚点中将其设置为false时,它找不到它,并且它从未设置。
我运行一个测试(从maplocationclose函数内),看看我能找到锚的任何数据属性,如:
console.log("Zoom Attr is: " + $('a.maplocation[anchorid="'+assocAnchorID+'"]').data('zoom'));
他们返回“未定义”。
即使它_did_工作(因为它为实际的属性),这将是'$(” .maplocation [data-anchorid =''+ assocAnchorID +'“]')...' – Mackan
@Mackan值得注意的是,我猜是的。 – George
我对此很感兴趣,所以请原谅任何错误,但也许我会用'console.log'示例将焦点从现有问题转移到现有问题上。如果这部分是一个错误,使用'data- *'属性,我会纠正它,尽管可能应该不在本例中。我的问题是从'maplocationclose'函数设置'mapopen'属性,它什么也不做。我相信我专门为我的'mapopen'属性使用数据缓存。你的理由是否仍然适用?感谢您的建议。 – biscuitstack