2017-03-06 176 views
0

我需要从html传递一个值并使用它在我的Js中查找var,因此根据我的html上的theId中的值,我可以在我的js中使用该var。我怎样才能做到这一点?在js中使用通过的val

HTML

<input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist 

<script>对HTML标签

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"} 
+0

* “将是不确定的” *那不可能。它应该会抛出一个错误。 'Waist.val();'相同。 **字符串**没有'val()'方法。 (但是,'Waist'有可能指DOM元素而不是字符串)。 –

回答

0

你应该避免使用onclick属性,而是倾听事件“js side”(addEventListener/attachEvent)。 在那些事件处理的上下文中,通常表示事件监听器已被连接到所述元件:

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

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

我需要使用传递给我的函数的值,因为它是我的js.file中的一个var。 – Damkulul

0

的正确方法继续进行,这是:

代替的var temp1 = theId.val();

使用document.getElementById(theId).value

+0

temp1 is undifiend .. – Damkulul

+0

使用'var temp1 = document.getElementById(theId).value;'并在下一行使用'console.log(temp1);'它会显示值 –

0

当你这样做:theId.val(),它是有意义的,它是undefined。调用getToWork(this.id)发送字符串,而不是HTML元素。因此,在字符串上调用.val()是未定义的。

如果你想获取存储在被按下,您需要更改的复选框元素的文本值...

function getToWork(arg) { 
 
    console.log(document.getElementById(arg).value); 
 
}
<input id="Waist" type="checkbox" value="INPUT_BOX" onchange="getToWork(this.id)"> Waist

1

的问题与您的代码是,您不使用的document.getElementById如下:

JS:

document.getElementById("Waist").addEventListener("change",function(evt){ 
    getToWork(this.id); 
}) 

function getToWork(theId){ 
    usedCheckBox(theId); 
} 

function usedCheckBox(theId){ 
    console.log(theId); 
    console.log(Waist); 
    var temp1 = document.getElementById("Waist").val; // will return Waist 
    var temp2 = Waist.val(); // generate error, don't know what you want 
} 

var Waist = "change today!" 

小提琴: https://jsfiddle.net/xLvzah8w/1/

我现在明白你的问题,并为您应该创建一个父对象,如图所示:

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'是一个值为'腰部'的字符串,其中腰部是发生错误的对象。

更新小提琴:https://jsfiddle.net/xLvzah8w/2/

+0

我需要使用该值传递给我的函数,因为它是我的js.file中的一个var – Damkulul