我遇到了一些基本的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