我被困在試圖在我創建的iFrame上設置data()
。如何在iFrame body標籤上設置jQuery數據()並從iFrame中檢索它?
這是我在做什麼:
// options > my configuration object
// options.src = eg "path/foo.html"
// options.id = uuid
// options.parent = $(elem)
// options.param = JSON object
newHTML = document.createElement("iframe");
newHTML.setAttribute("src", options.src);
newHTML.setAttribute("frameborder", 0);
newHTML.setAttribute("seamless", "seamless");
newHTML.setAttribute("data-id", options.id);
newParentElement = options.parent.parent()[0];
options.parent.replaceWith(newHTML);
// select
newRootElement = newParentElement.querySelectorAll(
'[data-id="'+options.id+'"]'
);
// add configuration
$(newRootElement[0]).load(function() {
var newElement = $(this);
if (options.param) {
newElement.contents().find("body").attr("foo","bar").data("config", options.param);
}
});
當我看着我的iframe和它的機身標籤,該attr("foo")
設置正確,我也安慰它,如下所示:
console.log(newElement.contents().find("body").attr("foo"));
但是當我嘗試使用任何data()
或data("config")
勸慰config
,像這樣:
console.log(newElement.contents().find("body").data("config"));
它總是返回undefined
問題:
爲什麼不能設置一個jQuery data()
的iframe?或者我做錯了什麼?
感謝您的幫助!
是options.param一個有效的字符串?爲什麼你不使用jQuery語法來處理你的所有腳本?會更容易:) – Alex
jQuery不會將數據與元素本身一起存儲。它只是用元素存儲一個'id'。數據本身存儲在'jQuery.cache'中。如果您使用父對象的「jQuery」對象設置iframe外部的數據,則會在父對象中設置_lives_並且無法使用帶iframe的jQuery對象的.data來檢索數據。那是因爲兩個jQuery對象不共享他們的'.cache'對象。 –
@ t.niese:啊。謝謝。你能回答一下嗎,我可以檢查嗎? – frequent