构建一个函数来从一组元素返回元素的索引。 但是当我尝试将值传递给另一个变量(myindex)时,我确实得到了未定义。
这里是Javascript源代码
$(document).ready(function(){
$("[id*='_CG']").addClass("form-control input-sm text-right");
$("[id*='_Weight']").addClass("form-control input-sm text-right");
$("[id*='TXFuelWeight']").addClass("form-control input-sm text-right");
$("[id*='TRPFuelWeight']").addClass("form-control input-sm text-right");
myindex = GetLSElementIndex("[id*='W_OP_']", "W_OP_CAB1Items");
alert (myindex);
});
// Get the index element in a group of element
function GetLSElementIndex(ElementGroup, Element) {
$(ElementGroup).each(function (index) {
var someText = $(this).attr('id');
if (someText == Element) {
alert(someText);
alert(index);
//GetLSElementIndex = index;
//alert(GetLSElementIndex);
return ;
//return index;
}
});
}
答案 0 :(得分:0)
你需要像这样使用:
var indx;
if (someText == Element) {
alert(someText);
alert($('#'+Element).index());//Don't do just alert(index)
indx = $('#'+Element).index();//I need to find index of ? #W_OP_CAB1Items
return indx;
}
答案 1 :(得分:0)
function GetLSElementIndex(ElementGroup, Element) {
var value = -1; //If no element is found, index is assumed to be -1
$(ElementGroup).each(function (index) {
var someText = $(this).attr('id');
if (someText == Element) {
alert(someText);
value = index;
alert(value);
return false;//To break out of each() once the index is found.
}
});
return value; //Return the value (from the called fn) once the processing is done
}
答案 2 :(得分:0)
通过为该方法定义一个全局变量并将GetLSElementIndex
循环的索引指定给它并返回它然后将return语句从{{1}中移出来重写这样的each
方法}循环。
DEMO:FIDDLE
each
注意:此方法仅返回// Get the index element in a group of element
function GetLSElementIndex(ElementGroup, Element) {
var setIndex;
$(ElementGroup).each(function (index) {
var someText = $(this).attr('id');
setIndex = index;
if (someText == Element) {
alert(someText);
alert(index);
}
});
return setIndex;
}
循环的最后一项的索引。
答案 3 :(得分:0)
你必须打破“Jquery each”并返回索引。混淆点是“Jquery each”打破“return false”声明。 您必须将索引值存储在某个局部变量中(var toReturn ..在下面的函数中)。这是修改后的GetLSElementIndex函数
// Get the index element in a group of element
function GetLSElementIndex(ElementGroup, Element) {
var toReturn;
$(ElementGroup).each(function (index) {
var someText = $(this).attr('id');
if (someText == Element) {
//alert(someText);
// alert(index);
toReturn= index;
//GetLSElementIndex = index;
//alert(GetLSElementIndex);
return false ;
//return index;
}
});
return toReturn;
}
有关详细信息,请关注other question of Stack Overflow
答案 4 :(得分:0)
更新函数以将所需元素的索引存储在变量中,然后返回变量。
function GetLSElementIndex(ElementGroup, Element) {
var elementIndex;/* store the index of #element here */
$(ElementGroup).each(function (index) {
var someText = $(this).attr('id');
if (someText == Element) {
elementIndex = index;
}
});
return elementIndex; /* will return index of #element if found otherwise will return undefined */
}
已删除所有警报,因为我认为这些警报是出于调试目的。