我有一个跨度,里面有一个文本,就像:
<span class="characters-count">(160 Characters Left)</span>
当我尝试使用类选择器( .characters-count
)来获取span中的文本时,给出了一个类(在本例中是一个类):
$(".characters-count")[0].text();
它返回未定义的!
然而,这个选择器工作得很好:
$("span.characters-count").text();
谁能解释这是怎么回事?
发布于 2015-03-23 22:55:39
$("span.characters-count").text();
在本例中,您使用的是具有jQuery方法的text
对象。
$(".characters-count")[0].text();
在本例中,您使用的是没有实际DOM元素方法的text
(如document.getElementByClassName('characters-count')[0]
)
发布于 2015-03-23 22:55:08
发布于 2015-03-23 22:56:45
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">(160 Characters Left)</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
);
https://stackoverflow.com/questions/29226572
复制