你不需要id是一个全局变量,我看不出如何有利于所有。
它的记录未定义,因为它在调用时未定义,您只能在调用click事件后设置该值。
$(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.
其中一个最重要的原因,加上“身份证”作为一个全球性的是一个坏主意,就是你可以结束了,有很多的任意值填充全局命名空间,没有结构,因此很难维护代码,您可能会冒险覆盖全局名称空间上的重要属性,这可能会导致您的网站/应用程序中出现未定义的行为。
使用单个全局对象是利用全局名称空间的可接受方式,而不会冒意冒犯其他变量的意外覆盖,而且它也更容易调试您的Apps变量。 (大概)只会记录你的应用程序创建的变量,因此你不需要通过许多其他变量来查找你的应用程序。
如果您使用我上面的代码的建议,比较这两个日志:
console.log(window.App);
console.log(window); //The global namespace
你应该看到的是,第一个日志打印你出一个漂亮的,干净的物体只是你的变量“ID”里面,你应该在第二个日志中看到一吨变量,事实上,你甚至可能不得不在控制台中向下滚动以找到你的'id'变量。
第一:点击是一个事件,你是在事件注册不执行后记录id。 第二:使用JavaScript命名空间模式,而不是把它放在全局范围之下。 –
也看看:https://api.jquery.com/selected-selector/ – Felix