简体   繁体   English

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

[英]Why does this JQuery code give me a undefined?

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

I am using the above code to get a selected option from a dropdown and then use that variable as a global variable in all my JS files. 我正在使用上面的代码从下拉列表中选择一个选项,然后将该变量用作我所有JS文件中的全局变量。 However, this is giving me an undefined in the console. 但是,这在控制台中给了我一个undefined的信息。 How do I get id to behave as a global variable in all my JS files.? 如何在所有JS文件中获取id使其充当全局变量?

You don't need id to be a global variable, I can't see how that would be advantageous at all. 您不需要将id用作全局变量,我完全看不出这将是多么有利。

It's logging undefined because it's undefined when you call it, you only set the value after the click event has been called. 它记录的是未定义的,因为调用时是未定义的,只有在单击事件被调用后才设置该值。

$(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'
});

This is what's happening with your code at the minute 这就是您的代码目前正在发生的情况

$(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. 
});

Although outside of the scope of your question, in answer to your comment, to make id a global variable, I would add one global variable, rather than just a random 'id' property. 尽管不在您的问题范围内,但为了回答您的评论,要使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.

One of the most important reasons why adding 'id' as a global is a bad idea, is that you can end up populating the global namespace with lots of arbitrary values, there's no structure, thus it's hard to maintain the code, and you risk overwriting an important property on the global namespace, which could cause undefined behaviour in your website/App. 为何将'id'添加为全局变量最重要的原因之一是,您最终可能会用很多任意值填充全局命名空间,没有结构,因此很难维护代码,并且您要冒风险覆盖全局名称空间上的重要属性,这可能会在您的网站/应用中导致未定义的行为。

Having a single global object is an acceptable way of utilising the global namespace, without risking the accidental overrides to other variables, and it's also a lot easier to debug your Apps variables. 使用单个全局对象是使用全局名称空间的一种可接受的方式,而不会冒意外覆盖其他变量的风险,并且调试Apps变量也容易得多。

A single log of the App object (call it whatever you like), will (presumably) log only the variables your app has created, thus you're not having to look through many other variable to find yours. 一个App对象的日志(随便叫什么),(大概)只会记录您的应用程序创建的变量,因此您不必遍历许多其他变量来查找您的变量。

If you used my code suggestion above, compare these two logs: 如果您使用了上面的代码建议,请比较以下两个日志:

console.log(window.App); 

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

You should see that the first log prints you out a nice, clean object with just your variable "id" inside, you should see a tonne of variables in the second log, in fact, you may of even had to scroll down in the console to find your 'id' variable. 您应该看到第一个日志将您的变量“ id”打印在一个漂亮,干净的对象中,第二个日志中您应该看到一吨变量,实际上,您甚至可能需要在控制台中向下滚动查找您的“ id”变量。

id is a local variable available only withing your $(document).ready() function. id是一个局部变量,仅在$(document).ready()函数中可用。 If you want to have global access, then define it outside of any functions. 如果要具有全局访问权限,请在任何功能之外定义它。 This should fix your problem. 这应该可以解决您的问题。 You can read more about scopes Here . 您可以在此处阅读有关范围的更多信息。

Hope this helps! 希望这可以帮助!

your code will be undefined is right. 您的代码将未定义是正确的。 because when page load but user don't click on $('.dropdown-menu a') and then no value for id variable. 因为当页面加载但用户不要单击$('。dropdown-menu a')时,id变量没有值。

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

If you still want to see value of variable you can fix like this 如果您仍然想查看变量的值,可以像这样修复

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

Hope this help!!! 希望这个帮助!!! =) =)

Because the value of id changes only when you click $('.dropdown-menu a') But in your ready function you print out without any condition. 因为id的值仅在单击$('.dropdown-menu a')时更改,但是在ready函数中,您无条件打印。 You defined the var id inside the ready function and then defined a function that occurs only on a click event and then print out the id . 您在ready函数中定义了var id ,然后定义了仅在click事件上发生的函数,然后打印出id In between the definition of the var id and the printing its value no click occured so nothing changed therefore it's still undefined. 在var id的定义和打印其值之间,没有单击发生,因此没有任何更改,因此仍然是未定义的。 If you want to see what's the value of id after clicking modify your code to : 如果要在单击将代码修改为之后查看id的值,请执行以下操作:

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

This will print the value in console after clicking .dropdown-menu a 单击.dropdown-menu a后,这将在控制台中打印值

var globalScope = globalScope || {};

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

warning: click is an event, you are logging id after the event registration not execution. 警告:单击是事件,事件注册未执行后,您正在登录ID。 Put it in your event if you want to log it every click, after the new association. 如果要在新关联之后每次单击记录日志,请将其放在事件中。

use javascript namespacing pattern rather than delcare it out of the function, just to prevent future issues and to orgainze your data. 请使用javascript名称间隔模式,而不要在函数中删除它,只是为了防止将来出现问题并整理您的数据。

$(function()   // jquery
{
   $("#id Your Checkbox").Change(function()
    {
           var id = $(this).Val();
           // now , you can use of id.
           $("#test").text(id);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM