数组中的字符串不再是jQuery.each()之后的字符串 [英] Strings in array are no longer strings after jQuery.each()
问题描述
当我通过jQuery.each()
方法循环它们时,我对字符串数组的行为感到非常困惑.显然,字符串成为回调函数中的jQuery对象.但是,我无法使用this.get()
方法来获取原始字符串.这样做会触发 this.get不是函数错误消息.我想原因是它不是DOM节点.我可以做$(this).get()
,但是它使我的字符串变成了一个数组(从"foo"
到["f", "o", "o"]
).
I'm pretty confused with the behaviour of arrays of strings when I loop them through the jQuery.each()
method. Apparently, the strings become jQuery objects inside the callback function. However, I cannot use the this.get()
method to obtain the original string; doing so triggers a this.get is not a function error message. I suppose the reason is that it's not a DOM node. I can do $(this).get()
but it makes my string become an array (from "foo"
to ["f", "o", "o"]
).
如何将其转换回字符串?我需要获取String
类型的变量,因为我将其传递给其他函数来比较它们之间的值.
How can I cast it back to string? I need to get a variable of String
type because I pass it to other functions that compare the values among them.
我附上了一个独立的测试用例(需要Firebug的控制台):
I enclose a self-contained test case (requires Firebug's console):
<!DOCTYPE html>
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function(){
var foo = [];
var $foo = $(foo);
foo.push("987");
$foo.push("987");
foo.push("654");
$foo.push("654");
$.each(foo, function(i){
console.log("foo[%d]: object=%o; value=%s; string=%o", i, this, this, $(this).get()); // this.get() does not exist
});
$foo.each(function(i){
console.log("$foo[%d]: object=%o; value=%s; string=%o", i, this, this, $(this).get()); // this.get() does not exist
});
});
//--></script>
</head>
<body>
</body>
</html>
推荐答案
edit/clarification:calllback函数有两个参数,第二个是变量的值.用它代替this
我已经测试了这两种变体,并且一切似乎都按预期工作(字符串仍然是字符串).
edit/clarification: calllback functions takes two arguments, the second one is value of the variable. Use it instead of this
I have tested both variants and everything seems to work as expected (strings are still strings).
>>> $.each(['foo','bar'], function(i, s){ console.info( s, typeof s ) })
foo string
bar string
>>> $(['foo','bar']).each(function(i, s){ console.info( s, typeof s ) })
foo string
bar string
这篇关于数组中的字符串不再是jQuery.each()之后的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!