在js中使用传递的val

时间:2017-03-06 16:04:20

标签: javascript jquery html

我需要从html传递一个值并使用它来查找我的Js中的var,所以根据我的html中的 theId 中的值,我可以使用我的js中的var。我怎么能这样做?

HTML

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

<script>标记

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

4 个答案:

答案 0 :(得分: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"}
}

您的代码无法正常工作的原因是您尝试访问字符串的属性。 &#39; theId&#39;是一个有价值的字符串&#39;腰围&#39;腰部是一个物体,所以发生错误。

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

答案 1 :(得分:0)

你应该避免使用onclick属性,而是倾听事件&#34; js side&#34; (的addEventListener /的attachEvent)。 在这些事件处理程序的上下文中, this 通常表示事件侦听器附加到的元素:

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

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

答案 2 :(得分:0)

正确的方法是:

取代var temp1 = theId.val();

使用document.getElementById(theId).value

答案 3 :(得分: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