2017-08-09 44 views
0

我输入了几个输入字段,用户可以在第一次访问特定页面时输入值,这些值将保存到数据库,并且每当您调用函数时在文本框中输入一个值,因为它将显示总数中5个值的百分比。计算标签和文本框的百分比

当用户离开表单并返回时,将显示标签而不是文本框。对于这样的任务,下面的代码是正确的方向,它会动态地选择正确的参数“.text”或“.val”来获取值,因为下次用户回来时会填充标签?我想自动执行此过程,而不是自己附加每个标签值。

我已标记那里我有麻烦

function calcABC(e) { 

//Declare array of numeric selectors 
var arr = ["a", "b", "c", "d", "e"]; 
var x = ""; 
var y = ""; 
if (e == "label") { 
    x = "lbl_" 
    y = ".text()"; 
} 
else { 
    x = "txt_" 
    y = ".val()"; 
} 

//HAVING TROUBLE HERE VVVVVVV 
alert(eval("$('#' + x + arr[0]) + y)")); 
alert("hello"); 

//loop through the array and get the value for that array index 
var before = 0; 
for (var i in arr) 
{ 
    before += isNaN(parseInt($("#"+ x + arr[i]).val())) ? 0 : parseInt($("#" + arr[i]).val()) 
} 

//Apply the total to the global variable 
ABCTotal = before; 

//Loop through the numbers and get the precentage value and append the value to the relevant area 
for (var j in arr) 
{ 
    console.log($("#" + x + arr[i]).val()) 
    var val = isNaN(parseInt($("#" + x + arr[j]).val())) ? 0 : parseInt($("#" + arr[j]).val()); 
    $("#txt" + arr[j] + "Prec > small").text(calcPrec(val).toFixed(2) + "%"); 
} 

//Set the total field 
$("#txt_ABCTotal").text(ABCTotal); 
} 
// Nice function to quickly calculate the precent value from a total 
function calcPrec(val) 
{ 
    return (val * 100)/ABCTotal; 
} 

我希望是有道理的!反正任何帮助拨款!

+0

您问东西,然后给你迄今为止的解决方案。您应该添加不适用于您当前解决方案的内容。 – MisterJ

+0

更新了我无法解析jquery参数以供阅读的代码。 (特别是警报) – imBlue

+0

为了避免使用eval,强烈推荐我会做'y ='text''或'y ='val'',然后'$('#'+ x + arr [0] )[y]()' 虽然你的具体问题是什么,你会得到什么错误? – MisterJ

回答

0

要避免使用eval,这是强烈建议最好是做Y =“文本”或y =“VAL”,然后调用函数与数组方式一样的:

$('#' + x + arr[0])[y]()