gpt4 book ai didi

javascript - 为什么这个 JQuery 代码给我一个未定义的?

转载 作者:行者123 更新时间:2023-11-30 07:12:57 26 4
gpt4 key购买 nike

$(document).ready(function () {
var id;
$('.dropdown-menu a').click(function () {
id = $(this).text();
$('#selected').text($(this).text());
});
console.log(id);
});

我使用上面的代码从下拉列表中获取选定的选项,然后将该变量用作我所有 JS 文件中的全局变量。但是,这在控制台中给了我一个 undefined 。如何让 id 在我的所有 JS 文件中充当全局变量?

最佳答案

你不需要 id 成为一个全局变量,我完全看不出这有什么好处。

它记录未定义,因为当你调用它时它是未定义的,你只能在调用点击事件后设置值。

$(document).ready(function () {
var id = "foo";
$('.dropdown-menu a').click(function () {
id = $(this).text();
$('#selected').text($(this).text());

console.log(id); // This will now log whatever was in your text value
});
console.log(id); //This will now log 'foo'
});

这就是您的代码当时正在发生的事情

$(document).ready(function () {

//You're not passing id a value, so it gets initialised as undefined.
var id;

$('.dropdown-menu a').click(function () {
id = $(this).text();
$('#selected').text($(this).text());

console.log(id); // This will now log whatever was in your text value
});

//The click event hasn't been called yet, so id is still undefined.
console.log(id);

//You've only assigned a click event above, you didn't call it, id will
//not get set until '.dropdown-menu a' has been clicked.
});

虽然超出了您的问题范围,但在回答您的评论时,为了使 id 成为一个全局变量,我会添加一个全局变量,而不仅仅是一个随机的“id”属性。

$(document).ready(function () {
var App = window.App || (window.App = {});

App.id = "foo";

$('.dropdown-menu a').click(function () {
App.id = $(this).text();
$('#selected').text($(this).text());

console.log(App.id); // This will now log whatever was in your text value
});
console.log(App.id); //This will now log 'foo'
});




//In some other JS file on your webpage / in scope
var App = window.App || (window.App = {});

console.log(App.id); //This should log the ID, providing it was called after the above code.

将“id”添加为全局变量是一个坏主意的最重要原因之一是,您最终可能会用大量任意值填充全局命名空间,没有结构,因此很难维护代码,并且您可能会覆盖全局命名空间中的重要属性,这可能会导致您的网站/应用出现未定义的行为。

拥有一个全局对象是一种可以接受的利用全局命名空间的方式,没有意外覆盖其他变量的风险,而且调试您的 Apps 变量也容易得多。

App 对象的单个日志(随便你怎么调用它)将(大概)只记录你的应用程序创建的变量,因此你不必查看许多其他变量来找到你的变量。

如果您使用了我上面的代码建议,请比较这两个日志:

console.log(window.App); 

console.log(window); //The global namespace

你应该看到第一个日志打印出一个漂亮、干净的对象,里面只有你的变量“id”,你应该在第二个日志中看到大量变量,事实上,你甚至可能不得不向下滚动在控制台中找到您的“id”变量。

关于javascript - 为什么这个 JQuery 代码给我一个未定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46214148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com