[英]Jquery get text value of some selector using index in array
There is the following code with jQuery: jQuery有以下代码:
var ths = $(".timetable__table th");
var th;
for (var i = 0; i < ths.size(); i++) {
th = ths.get(i).text();
console.log(th);
}
When I try to execute this code I get the following exception: TypeError: ths.get(...).text is not a function
. 当我尝试执行此代码时,我得到以下异常:
TypeError: ths.get(...).text is not a function
。 I don't understand why it occurs, I just need to get the text value of a tag. 我不明白为什么会发生,我只需要获取标签的文本值。 How can I fix it?
我该如何解决?
Do like this, Use .each()
function at this context to traverse over a collection of jquery object. 这样做,在此上下文中使用
.each()
函数遍历jquery对象的集合。
$(".timetable__table th").each(function(){
console.log($(this).text());
});
.get(index)
would return a javascript object and that does not contains a function called .text()
.get(index)
将返回一个javascript对象,并且不包含名为.text()
的函数
Note: Keep in mind that .size()
has been deprecated from the version 1.8 use .length
instead 注意:请记住,
.size()
已从版本1.8使用.length
弃用
because .get() returns the dom element not a jQuery object(the .text()
is a method of jQuery wrapper object) use .eq() which will return a jQuery object 因为.get()返回dom元素而不是jQuery对象(
.text()
是jQuery包装器对象的方法)使用.eq()将返回一个jQuery对象
var ths = $(".timetable__table th");
var th;
for (var i = 0; i < ths.size(); i++) {
th = ths.eq(i).text();
console.log(th);
}
.get()
returns the underlying DOM element(s), which don't have a text() method. .get()
返回没有text()方法的底层DOM元素。 Use .eq()
instead. 请改用
.eq()
。
Looks like you didn't decide if you want to use the DOM or jQuery. 看起来你没有决定是否要使用DOM或jQuery。 Your code can be simplified to something like:
您的代码可以简化为:
$(".timetable__table th").each(function(index, el) {
console.log($(el).text());
});
You need to iterate array like th[i]
: 你需要像
th[i]
一样迭代数组:
var ths = $(".timetable__table th");
var th;
for (var i = 0; i < ths.size(); i++) {
th = ths[i].text();
console.log(th);
}
But easiest way is below where you can skip for loop and simply use .each
: 但最简单的方法是在下面你可以跳过循环并简单地使用
.each
:
$(".timetable__table th").each(function(){
console.log($(this).text());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.