var checkedIds=""; //翻页保存选中的id
/**
* 记录选择的元素
* @return
*/
function changeIds(){
var oneches=document.getElementsByName("ids");
for(var i=0;i<oneches.length;i++){
if(oneches[i].checked==true){
//避免重复添加(若存在元素时,不添加)
if(!contains(checkedIds,oneches[i].value)){
checkedIds+=oneches[i].value+",";
//console.log(oneches[i].value);
}
}
if(oneches[i].checked==false){
//取消复选框时 含有该id时将id从全局变量中去除
if(contains(checkedIds,oneches[i].value)){
checkedIds=checkedIds.replace((oneches[i].value+","),"");
}
}
}
}
/**
*
* @return
*/
function getChecked(){
if(checkedIds==""){
return;
}
var oneches=document.getElementsByName("ids");
for(var i=0;i<oneches.length;i++){
//全局变量中含有id,则该复选框选中
if(contains(checkedIds,oneches[i].value)){
oneches[i].checked="checked";
//console.log(oneches[i].value);
}
}
}
/**
* 判断数组是否存在元素
* @param obj
* @param ele
* @return
*/
function contains(obj, ele) {
//console.log(obj);
//console.log(ele);
if(obj==""){
return;
}
/*若参数obj为字符串时,需要转换成数组*/
var arr = obj.split(",");
var i = arr.length;
while (i--) {
if (arr[i] == ele) {
return true;
}
}
return false;
}
onclick="changeIds();getChecked();contains('1','2');"
错误信息
Uncaught TypeError: Failed to execute 'contains' on 'Node': parameter 1 is not of type 'Node'.
别这么写,这是不推荐的写法,而且容易出现很多问题。
在 html 中写:
在 js 中写:
你写
onclick="contains('1','2');"
时,这个 contains 函数的调用环境变成了当前的元素,而元素的类型是HtmlElement
也是Node
。非常巧合的是,Node
上面也有一个函数contains
,所以程序以为你调用的是Node
上的contains
,因此出现了参数类型不匹配的错误。