Javascript 在js中使用传递的val

Javascript 在js中使用传递的val,javascript,jquery,html,Javascript,Jquery,Html,我需要从html中传递一个值,并使用它在我的Js中找到一个var,因此根据html中theId中的值,我可以在我的Js中使用var。我该怎么做 HTML <input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist function getToWork(theId){ usedCheckBox(theId); } myJs.js function usedCheckBox(theId){

我需要从html中传递一个值,并使用它在我的Js中找到一个var,因此根据html中theId中的值,我可以在我的Js中使用var。我该怎么做

HTML

 <input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist 
function  getToWork(theId){
  usedCheckBox(theId);
}
myJs.js

  function usedCheckBox(theId){

    var temp1 = theId.name; - will be undefined
    var temp2 = Waist.name; - will work
}

var Waist = {name:"bob",age:"17"}

您应该避免使用onclick属性,而是侦听事件“js-side”(addEventListener/attachEvent)。 在这些EventHandler的上下文中,这通常表示事件侦听器已附加到的元素:

document.getElementById("Waist").addEventListener("change",getToWork);

function getToWork(){
    usedCheckBox(this);
}
function usedCheckBox(elem){
    var value = elem.value ;
}

正确的方法是:

代替
var temp1=theId.val()


使用
document.getElementById(theId).value

当您这样做时:
theId.val()
,它是
未定义的
。调用
getToWork(this.id)
发送的是字符串,而不是HTML元素。因此,对字符串调用
.val()
是未定义的

如果您试图获取存储在按下的复选框元素中的文本值,则需要更改为

函数getToWork(arg){
log(document.getElementById(arg.value);
}

腰部
代码的问题是,您没有使用document.getElementById,如下所示:

JS:

小提琴:

我现在理解了您的问题,因此您应该创建一个父对象,如图所示:

function usedCheckBox(theId){
    var temp1 = parent[theId].name; // will return bob
    console.log(temp1);
    var temp2 = parent.Waist.name; // will return bob
        console.log(temp2);
}

var parent = {
  Waist : {name:"bob",age:"17"}
}
代码无法工作的原因是您试图访问字符串的属性。”theId'是一个值为'sheeld'的字符串,其中sheeld是一个对象,因此会发生错误。


更新的fiddle:

“将是未定义的”,无法定义。它应该抛出一个错误。与
sheeld.val()相同。字符串没有
val()
方法。(但是,有可能
引用的是DOM元素而不是字符串)并在下一行中使用
console.log(temp1)它将显示值我需要使用传递给函数的值,因为它是我js.file中的一个var。我需要使用传递给函数的值,因为它是我js.file中的一个var
function usedCheckBox(theId){
    var temp1 = parent[theId].name; // will return bob
    console.log(temp1);
    var temp2 = parent.Waist.name; // will return bob
        console.log(temp2);
}

var parent = {
  Waist : {name:"bob",age:"17"}
}