我确实关注了SO的其他一些答案,from one of them我找到了我在这里使用的那个,但看起来它永远不会发生,因为这不是正常应该return false;
console.log(myId);
。
let pattern = new RegExp('^\/wiki\/');
var total = doSelect("Location").siblings('td').find('a').length;
doSelect("Location").siblings('td').find('a').each(function(i, el, index) {
var result = $(this).attr('href').replace(pattern, '');
console.log(result);
if (index === total - 1) {
myId = item.pageid;
console.log(myId);
return false;
}
});
我甚至按照this other SO answer的建议尝试了以下操作,没有任何积极的结果:
let pattern = new RegExp('^\/wiki\/');
doSelect("Location").siblings('td').find('a').each(function(i, el) {
var result = $(this).attr('href').replace(pattern, '');
console.log(result);
}).promise().done( function(){
myId = item.pageid;
console.log(myId);
return false;
});
更新
关于:item
(以下数据没有问题),上面的代码在以下data each
中:
$.getJSON(url,function(data){
$.each(data, function(i, item) {
答案 0 :(得分:2)
each()
回调没有第三个参数。您所指的index
未定义。第一个参数i
是索引
更改为:
if (i === total - 1)
答案 1 :(得分:2)
您的第一个选项有一个sintax错误:
.each(function(i,el,index)必须是.each(function(index,el)
let pattern = new RegExp('^\/wiki\/');
var total = doSelect("Location").siblings('td').find('a').length;
doSelect("Location").siblings('td').find('a').each(function(index, el) {
var result = $(this).attr('href').replace(pattern, '');
console.log(result);
if (index === total - 1) {
myId = item.pageid;
console.log(myId);
return false;
}
});
答案 2 :(得分:1)
问题是变量index
未定义,因此if (index === total - 1)
永远不会返回true。
对函数.each
的调用:
.each(function(i, el, index)
应该是
.each(function(i, el)
那么测试应该是
if (i === total - 1)
cf jQuery API documentation,说明函数采用的两个参数:
.each(function)
function类型:Function(整数索引,Element元素)
答案 3 :(得分:0)
您还可以使用.last()
功能:
1
//insert own jq function
$.fn.myTask = function(){
myId = item.pageid;
console.log(myId);
//My suggestion: return this;
return false;
}
2
//than replace your lines
let pattern = new RegExp('^\/wiki\/');
var total = doSelect("Location").siblings('td').find('a').length;
doSelect("Location").siblings('td').find('a').each(function(i, el) {
var result = $(this).attr('href').replace(pattern, '');
console.log(result);
}).last().myTask();