在这里,我试图像在jquery中那样编写自定义的每个方法,为此在每个函数中,我检查对象是否与数组相似,是否像数组一样,我运行循环并通过在每个函数中发送参数来调用回调函数。在每个函数中,我都会获取正确的值,但在回调中,它们将返回未定义的值。
var obj = document.getElementsByTagName('input');
var isArrayLike = function(obj){
if(typeof obj.length === "number"){
if(obj.length===0){
return true;
}
else if(obj.length>=0){
return (obj.length)-1 in obj;
}
}
return false;
}
function cb(ob,ik){
//here value of ob is returning as 2 and id as undefined
console.log(ob)
console.log(ik)
if(document.getElementById(ik).checked){
console.log(ik)
}
}
function each (obj,cb) {
if(isArrayLike(obj)){
for(var i=0;i<obj.length;i++){
var id = obj[i].getAttribute('id');
cb.call(obj,id)
}
}
}
each(obj,cb)
问题是,call()
传递给obj
和时id
,的第一个参数call
将作为this
回调中的值传递,第二个参数将作为第一个参数的值传递,依此类推。因此,在您的情况下,obj
将传递为的值,this
将id
传递作为的值ob
,因此ik
由于未传递任何值,因此变得不确定。
一种解决方案是使用this
引用回调中的当前元素,另一种解决方案是将obj[i]
as作为this
值和第一个参数传递。
cb.call(obj[i], obj[i], id)
由于您将dom对象本身传递给了回调,因此无需传递id
var obj = document.getElementsByTagName('input');
var isArrayLike = function(obj) {
if (typeof obj.length === "number") {
if (obj.length === 0) {
return true;
} else if (obj.length >= 0) {
return (obj.length) - 1 in obj;
}
}
return false;
}
function cb(ob) {
//here value of ob is returning as 2 and id as undefined
console.log(ob, this)
if (ob.checked) {
snippet.log(ob.id)
}
}
function each(obj, cb) {
if (isArrayLike(obj)) {
for (var i = 0; i < obj.length; i++) {
cb.call(obj[i], obj[i])
}
}
}
function testit() {
each(obj, cb)
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
<button onclick="testit()">Test</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句