简体   繁体   English

jQuery span类选择器

[英]jQuery span class selector

I have a span with a text inside it like : 我有一个跨度,里面有一个文本,如:

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

given the span a class in this case .characters-count , when i tried class selector using jQuery to get the text inside span : 给定span在这种情况下是.characters-count类,当我尝试使用jQuery的类选择器获取span内的文本时:

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

it returns undefined ! 它返回undefined!

However this selector works well : 但是,此选择器效果很好:

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

anyone can explain what is happening ? 任何人都可以解释发生了什么事?

你需要使用的innerText而不是文本()当您使用$(“字符数”)[0]检查DEMO

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

In our case you work with jQuery Object that has text method 在我们的例子中,您使用具有text方法的jQuery Object

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

In this case you work with actual DOM element (like document.getElementByClassName('characters-count')[0] ) that does not have text method 在这种情况下,您将使用没有text方法的实际DOM元素 (例如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> 

try something like this: 尝试这样的事情:

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

Check here, why it was not working for you. 检查这里,为什么它不适合您。

//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

); );

Use 采用

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

Demo 演示

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

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