从函数内部访问变量时,变量显示为未定义

时间:2020-05-17 01:14:12

标签: javascript

我的问题基本上归结为:为什么这不起作用(单击按钮时变量数据和我显示为未定义-查看声明变量x和y的行)

        function fill_transfer_request_notification(data) {
            notification_list = document.querySelector('.live_notify_list');
            notification_list.innerHTML = "";
            template_notification = document.querySelector('#template_notification');
            for (var i = 0; i < data.unread_list.length; i++) {
                msg = data.unread_list[i];
                list_item = template_notification.content.cloneNode(true);
                list_item.querySelector('.notification_verb').textContent = data.unread_list[i].verb;
                list_item.querySelector('.notification_username_link').setAttribute('href',data.unread_list[i].data.href);
                list_item.querySelector('.notification_username_link').textContent = data.unread_list[i].data.username + " ";
                list_item.querySelector('.profile_img_req').setAttribute('src', data.unread_list[i].data.image_path);
                var x = data;
                var y = i;
                list_item.querySelector('.accept_transfer_button').onclick = function(){
                    window.location.href = data.unread_list[i].data.href;
                };
                notification_list.appendChild(list_item);
            }
        }

这行得通吗?

        function fill_transfer_request_notification(data) {
            notification_list = document.querySelector('.live_notify_list');
            notification_list.innerHTML = "";
            template_notification = document.querySelector('#template_notification');
            for (var i = 0; i < data.unread_list.length; i++) {
                msg = data.unread_list[i];
                list_item = template_notification.content.cloneNode(true);
                list_item.querySelector('.notification_verb').textContent = data.unread_list[i].verb;
                list_item.querySelector('.notification_username_link').setAttribute('href',data.unread_list[i].data.href);
                list_item.querySelector('.notification_username_link').textContent = data.unread_list[i].data.username + " ";
                list_item.querySelector('.profile_img_req').setAttribute('src', data.unread_list[i].data.image_path);
                var x = data;
                var y = i;
                list_item.querySelector('.accept_transfer_button').onclick = function(){
                    window.location.href = x.unread_list[y].data.href;
                };
                notification_list.appendChild(list_item);
            }
        }

0 个答案:

没有答案