jquery .text()==不工作

时间:2015-06-08 19:21:24

标签: jquery

我这里有这个代码:

$('.navbar-collapse a').click(function (e) {
                var counter = 0;
                if($(this).text() == 'About Us'){
                        console.log('here');
                }
        });

但它不起作用,我不会在这里看到'在我的控制台中。

当我为文本执行console.log时,我可以看到文本'关于我们'我做错了什么?

2 个答案:

答案 0 :(得分:1)

原因是文本可能有一些前导或尾随空格,因此请使用trim()删除额外的空格:

$('.navbar-collapse a').click(function (e) {
                var counter = 0;
                if($(this).text().trim() == 'About Us'){
                        console.log('here');
                }
        });

答案 1 :(得分:0)

你可能有空格等,所以你需要.trim它将为你带来这些无效的部分。

试试这个。

$('.navbar-collapse a').click(function (e) {
                    var counter = 0;
                    var trim = $(this).text().trim();
                    if(trim == 'About Us'){
                        console.log('here');
                    }
            });