如何使用在另一个函数中声明的变量

嗨,

我想将全局变量称为“列表”并在此函数上声明其值,以便我也可以在另一个函数上使用它:

var lists; document.addEventListener("DOMContentLoaded", function(event) { var parentOfMyList = document.body; attributes: true, childList: true, subtree: true }; var callback = function(mutationsList) { for (var mutation of mutationsList) { if (mutation.type == 'childList') { var elt = document.getElementById("contents"); if (elt) { lists = elt.textContent; console.log(lists); observer.disconnect(); } } } }; var observer = new MutationObserver(callback); observer.observe(parentOfMyList, config); }); 

这个其他function:

 function playthis() { const input = lists; const sounds = input.toLowerCase(); console.log(sounds); } 

我尝试在变量“列表”之前删除“var”,但它没有用。 它说“输入”是未定义的。 怎么了?

谢谢

你为什么要做const input = lists; ? 你不能只是const sounds = lists.toLowerCase(); 。 如果变量不是全局变量,则会在const input = lists;上出现错误const input = lists; 。 你确定变量是一个字符串吗? 尝试在function playthis的顶部添加console.log(typeof lists)

您必须在全局范围中定义全局变量。 我无法连接上一个}); 在你的第一个代码部分。 它不会告诉var列表是在某个代码块中还是在全局范围内声明。 如果你可以发布完整的代码,就可以很容易地看到你调用它的函数的范围。我的意思是把它放在$(document).ready(function() { 。如果你已经显示完整的代码那么它会容易检测。请尝试下面的代码 –

 //Globally Defined var lists; $(document).ready(function() { document.addEventListener("DOMContentLoaded", function(event) { var parentOfMyList = document.body; attributes: true, childList: true, subtree: true }; var callback = function(mutationsList) { for (var mutation of mutationsList) { if (mutation.type == 'childList') { var elt = document.getElementById("contents"); if (elt) { lists = elt.textContent; console.log(lists); observer.disconnect(); } } } }; var observer = new MutationObserver(callback); observer.observe(parentOfMyList, config); }); function playthis() { const input = lists; const sounds = input.toLowerCase(); console.log(sounds); } 

如果这不能解决您的问题,请在下面更改代码。 我想在几个地方看到数据。

 var callback = function(mutationsList) { // In case mutationsList if JSON Object Otherwise just console mutationsList console.log(JSON.stringify(obj)); for (var mutation of mutationsList) { if (mutation.type == 'childList') { var elt = document.getElementById("contents"); console.log(elt); if (elt) { lists = elt.textContent; console.log(lists); observer.disconnect(); } } } };