天天看点

jquery each函数参数传递的问题

都知道each函数是一个很好的遍历方法,但有些时候需要传递些参数进去,这时就出现问题来了.

1.传递数组.

var

obj = { one:1, two:2, three:3};

each(obj,

function

(key, val) {

alert(key);

alert(val);

});

其中, obj是我们要传递的参数数组, key是数组的索引, val是数组的值

2.dom元素参数

如果你dom中有一段这样的代码

?

1 2 3 4

<

input

name

=

"aaa"

type

=

"hidden"

value

=

"111"

/>

<

input

name

=

"bbb"

type

=

"hidden"

value

=

"222"

/>

<

input

name

=

"ccc"

type

=

"hidden"

value

=

"333"

/>

<

input

name

=

"ddd"

type

=

"hidden"

value

=

"444"

/>

然后你使用each如下

?

1 2 3 4 5 6

$.each($(

"input:hidden"

),

function

(i,val){

alert(val);

alert(i);

alert(val.name);

alert(val.value);

});

3.字符串参数

但是有些时候需要传递一个字符串进去,循环替换或其他功能,这时候的参数就很不好传进去了,它不能直接传进each函数里面,需要在each外面另外赋值,each才能调用

如:

function changecolor (v) {
    var mm = v;
    $('.resultcontent').each(function () {
        edn = $(this).html();
        var b = '<strong style="color: #ff3928;font-size: 18px">' + mm + '</strong>'
        var reg=new RegExp(mm,"g");
        edn = edn.replace(reg, b);
        $(this).html(edn);
    });
    }      

该函数的功能是 将所有 class 为 resultcontent 的HTML内容里面的 v 全部替换为 酒红色的v.