Javascript 使用jQuery获取用户定义的名称

Javascript 使用jQuery获取用户定义的名称,javascript,jquery,html,Javascript,Jquery,Html,需要使用jquery按名称获取元素,为了获取名称值,它与samp(变量)连接在一起。无法形成名称元素。连接有一些问题,请帮助 $("input[name^='resource_" + samp + "_']") 完整代码: var samp = $(thisVal).attr('name'); //user defined name $("input[name^='resource_" + samp + "_']").each(function(key,val){ alert("

需要使用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");
});
尝试:


名称有问题,例如:“%name%”-不需要使用 右:
$(“输入[name^=resource_“+samp+”)
尝试:


名称有问题,例如:“%name%”-不需要使用
右:
$(“输入[name^=resource_“+samp+”)

是否具有所选
thisVal
元素的
name
属性?
以下是对我有效的属性。

是否具有所选
thisVal
元素的
name
属性?
以下是对我有效的方法。

因为我们无法确定值“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:

,因为我们无法确定值“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:

连接本身看起来很好。你对代码有什么特别的问题吗?你能提供一个HTML吗?但是我的警报(calcwk输入)没有被调用。dRight
samp
包含任何空格吗?连接本身看起来很好。你对代码有什么特别的问题吗?你能提供一个HTML吗?但是我的警报(calcwk输入)调用名是否未包含任何空格?名称有问题,如:'%name%'-如果值包含空格,则不需要使用“You do need to use
来包装该值。相同的问题警报不会触发名称错误,如:'%name%'-如果值包含空格,则不需要使用“You do need to use
来包装该值包含空格。未触发相同问题警报