简体   繁体   中英

why does the attr() work and text() doesn't under the same situation? jQuery

  1. Sorry for the poor title.

  2. I have assigned selectors to my variable and chain it with attr() and then a different place and chain it with text() but the text() part doesn't work and I don't really understand why.

Can someone please give me a hand on what's the difference that's making it not work?

var alertMsg = "";
var $closestLabel = $(this).closest('label');
$(".credit-error-msg").each(function(){
    // console.log($(this).closest('label').text());
    if($closestLabel.attr('for') != "billing-unit"){  //works here
        if($(this).text() != ""){
            alertMsg += $(this).closest('label').text().toUpperCase() + "\n"; //doesn't work here that I have to write the whole thing out
            val = false;
        }
    }
});

see where I assigned the selector var $closestLabel = $(this).closest('label'); this works perfectly when I use $closestLabel inside the if statement but when it's inside the second if statement I have to use $(this).closest('label').text() because $closestLabel.text() would not work.

But as I can see $(this).closest('label').text() == $closestLabel.text() and $(this).closest('label').attr() == $closestLabel.attr() isn't it?

Thanks in advance for any help.

In your case the $(this).closest('label') inside the each is not the same as var $closestLabel = $(this).closest('label');

this inside the .each is one of the elements matched by the selector ".credit-error-msg"

While this at this time: var $closestLabel = $(this).closest('label'); is probably the window object.

I said probably because i don't know where in the code, within which scope, you are calling this snippet.

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