如何使用$.each()与$().each

如何使用$.each()与$().each,第1张

如何使用$.each()与$().each()以及他们的区别

1、首先,说下
$.each(Arry/Object,function(index,val){

//index表示下标,val表示下标对应的值

})

下面是使用$.each()的几种类型,其中arr2与Obj2是常用的

<script>
/*
$.each(arry/object,function(index,val){//index表示下标,val表示对应数组或者对象下标所对应的值 })
*/
// 参数i为遍历索引值,n为当前的遍历对象.
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(index, val) {
console.log(index)//index表示下标
console.log(val)
}); var obj1 = {one:1,two:2,three:3,four:4}
$.each(obj1, function(index, vals) {
console.log("开始"+vals)
console.log("下标"+index)
});
var obj2 = [{name:"lxs",age:"10"},{name:"xiaomi",age:"100"},{name:"zhangsan",age:"34"},{name:"小米",age:"100"}]
$.each(obj2, function(i, valObj) {
console.log(valObj)
console.log(valObj.age)
console.log(valObj.name)
});
var arr2 = [[1,2],[4],[7,6,3],[9,3,4,5]]
$.each(arr2, function(i, val) {
// console.log(i)
console.log(val[0])
});
//在数据交互中使用demo

$('.btns').click(function() {
getReq();
});
function getReq(){
$.ajax({
url: '1.json',
type: 'post',
success:function(res){
console.log(res.data);
$.each(res.data, function(i, values) {
console.log(i)
console.log(values.sas);
var objHtml = htmlspecialchars_decode(values.sas)
$('.containerBox').append(objHtml)
});
},
error:function(e){
console.log(error)
}
});

}
// html转义
function htmlspecialchars_decode(string, quote_style) {
var optTemp = 0
, i = 0
, noquotes = false;
if (typeof quote_style === 'undefined') {
quote_style = 2;
}
string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
var OPTS = {
'ENT_NOQUOTES': 0,
'ENT_HTML_QUOTE_SINGLE': 1,
'ENT_HTML_QUOTE_DOUBLE': 2,
'ENT_COMPAT': 2,
'ENT_QUOTES': 3,
'ENT_IGNORE': 4
};
if (quote_style === 0) {
noquotes = true;
}
if (typeof quote_style !== 'number') {
quote_style = [].concat(quote_style);
for (i = 0; i < quote_style.length; i++) {
if (OPTS[quote_style[i]] === 0) {
noquotes = true;
} else if (OPTS[quote_style[i]]) {
optTemp = optTemp | OPTS[quote_style[i]];
}
}
quote_style = optTemp;
}
if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
string = string.replace(/&#0*39;/g, "'");
}
if (!noquotes) {
string = string.replace(/&quot;/g, '"');
}
string = string.replace(/&amp;/g, '&');
return string;
}

</script>

  2、$().each()用法
  $().each 在dom处理上面用的较多


如果页面有多个input标签类型为checkbox,对于这时用$().each来处理多个checkbook,例如:
  

$(“input[name=’ch’]”).each(function(i){
if($(this).attr(‘checked’)==true)
{
//一些 *** 作代码
}
回调函数是可以传递参数,i就为遍历的索引


  

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/587657.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存