需要使用 jquery 按名称获取元素,为了获取名称值,它与 samp (变量)连接。无法形成名称元素。连接存在一些问题,请帮忙。
$("input[name^='resource_" + samp + "_']")
完整代码:
var samp = $(thisVal).attr('name'); //user defined name
$("input[name^='resource_" + samp + "_']").each(function(key,val){
alert("calcwk entered");
if ($(this).val() === '') {
theVal = 0;
}
else {
theVal = parseInt($(this).val());
}
tot = tot + theVal;
alert("calcwk exit");
});
最佳答案
由于我们无法确定值“samp”将包含什么格式,因此我们需要确保该值正确地用正确的引号覆盖。
$('[property=value]');
工作时没有空格或者选择器无法立即知道属性值的结尾在哪里,而
$('[property=my value]');
混淆系统的解析器,因此您需要用引号正确“转义”或“包装”值,例如:
$('[property="my value"]');
这是我的代码版本以寻求帮助
var samp = $(thisVal).attr('name'), //user defined name
tot = 0 //define the total
;
$('input[name^="resource_' + samp + '_"]').each(function(key,val){
var theVal = $(this).val(); // do a jQuery call once per item
if (theVal === '') {
theVal = 0; // if this is text change to 0
}
tot += parseInt(theVal); // no need with else, parseInt everything
alert("calcwk exit");
});
作为示例,我创建了这个 JSFiddle:http://jsfiddle.net/fua9rtjd/
关于javascript - 使用 jQuery 获取用户定义的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31832913/