简体   繁体   中英

JavaScript “unexpected identifier” in each loop - Why am I getting this error? Simple demo code within

function printClassForAllDivs()
{
    var divs = $('div');
    divs.each(function{
        var klass = $(this).attr('class');
        console.log('div class = '+klass);
    });
}

It seems to me that this code should loop over all the divs and for each iteration of the loop a variable should be created to store the class, which is then printed to the console.

I'm afraid I don't understand something about how to use the anonymous function.

function printClassForAllDivs()
{
    var divs = $('div');
    divs.each(function{
        // what don't I understand about what I am permitted to do in here?
    });
}

Thanks.

divs.each(function{

应该是

divs.each(function(){

You are missing parentheses for the function inside divs.each .. See below,

divs.each(function (){

Change your code like below,

function printClassForAllDivs()
{
    var divs = $('div');
    divs.each(function (){
        var klass = $(this).attr('class');
        console.log('div class = '+klass);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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