jQuery 跨度 class 选择器

jQuery span class selector

我有一个 span,其中包含如下文本:

<span class="characters-count">&#40;160 Characters Left&#41;</span>

给定跨度 class 在这种情况下 .characters-count ,当我尝试 class 选择器使用 jQuery 获取跨度内的文本时:

$(".characters-count")[0].text();

它 returns 未定义 !

但是这个选择器效果很好:

$("span.characters-count").text();

任何人都可以解释发生了什么?

使用 $(".characters-count")[0] 时需要使用 innerText 而不是 text() check DEMO

 $(".characters-count")[0].innerText
$("span.characters-count").text(); 

在我们的例子中,您使用具有 text 方法的 jQuery 对象

$(".characters-count")[0].text();

在这种情况下,您使用没有 text 方法

actual DOM element(如 document.getElementByClassName('characters-count')[0]

console.log($(".characters-count:first").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="characters-count">&#40;160 Characters Left&#41;</span>

尝试这样的事情:

$(".characters-count:first").text()

检查这里,为什么它不适合你。

//This will return dom element, so it doesn't have `text()` method, that's why it was throwing error for you.
    console.log($(".characters-count:first")[0]); 


// This will return object of an element, you can use jQuery selectors to get first element from collection and set text to it
     console.log($("span.characters-count"));
     console.log($("span.characters-count:first").text

);

使用

$(".characters-count").text();  

Demo