【发布时间】:2016-02-03 15:55:04
【问题描述】:
此代码最初确实按预期工作,但在昨天检查后,它在 Safari 中不再工作(它在 Chrome 和 Firefox 中仍然正常工作)。
这是我想要做的:我在可见函数之外声明变量“salonSelection”,然后我有一个单击函数,它在 salonSelection 中放置一个值。然后将 salonSelection 放入 localStorage。然后单击功能将窗口发送到新位置。这可以按预期工作,但 Safari 不会将变量传递到 click 函数之外。
这是代码,为了可读性,我尽可能多地注释。在最底部是什么给了我一个空值。提前感谢您的帮助:
var salonSelection
// fetch a list of salons in DB
allRef.child("salons").on('child_added', function(snapshot) {
// for each group, fetch the name and print it
var salonId = snapshot.key();
allRef.child("salons/" + salonId + "/salonName").once('value', function(snapshot) {
// Creates a new row for each item in table
var newRow = $('<tr>').text('').appendTo('#searchTable');
// Adds a cell for each salonName in row
var nameCell = $('<td>').text(snapshot.val()).appendTo(newRow);
// Adds an id of the salon name + 'Id' to each row
var cellId = nameCell.attr("id", snapshot.val().replace(/\s+/g, '') + "Id")
// Changes class of each cell
nameCell.addClass("text-left font-w600 text-primary");
// Passes clicked salon name to a variable for use on another page
$('#searchTable tr td').click(function(){
// Acquires text value of the specific td of tr
salonSelection = $(this)[0].childNodes[0].nodeValue
// Saves the variable to local storage
delete localStorage.salonSelection;
window.localStorage.salonSelection = salonSelection;
// Sends user to new location
window.location = 'base_pages_schedule_1.html';
});
});
});
// Attempting to retrieve the localStorage object, this is null in Safari only
$('#salon-name').click(function() {
console.log(localStorage.salonSelection)
})
在使用.data() 的建议之后,我添加了一些额外的代码进行测试。现在的结果是 undefined 正在记录到所有浏览器的控制台。
// Passes clicked salon name to a variable for use on another page
$('#searchTable tr td').click(function(){
// Acquires text value of the specific td of tr
salonSelection = $(this).text()
$(this).data("salonSelection", { name1: salonSelection});
test = $(this).data("salonSelection").name1;
// The value IS being stored and retrieved accurately here
console.log(test)
// Saves the variable to local storage
delete localStorage.salonSelection;
window.localStorage.salonSelection = salonSelection;
window.location = 'base_pages_schedule_1.html';
});
});
});
// Attempting to retrieve the .data() object, this is undefined
$('#salon-name').click(function() {
console.log(test)
});
经过仔细检查,重新启动 Safari 浏览器只允许整个功能正确运行一次(这是我提供的初始代码)。此后的每一次,$('#salon-name').click() 函数只记录第一次运行时存储的元素。
【问题讨论】:
-
这段代码的哪些部分与问题相关?有 DOM 操作、数据库查询和 localStorage 操作。请进行尽职调查并将其减少到最小的问题集。见how to ask 和creating an mcve。
-
感谢您的洞察力,我一定会在再次发布之前阅读这些内容!
标签: javascript firebase