Javascript未定义的变量,基本的html表单

时间:2014-12-20 13:24:29

标签: javascript html

我一直在努力解决这个问题大约一个小时,并且重写了三个不同的时间,我不能为我的生活弄清楚问题是什么,不管输入什么,除了名字之外的一切字段将返回一个值,但name将返回undefined。我已经这么多次了,我复制+粘贴+修改了工作,没有一个错字我能找到......这里发生了什么?

Item Name: <input type="text" id="item_name" placeholder="Enter a price..."/> </br>
Item Price: <input type="text" id="item_price" placeholder="Enter a price..."/> </br>
Item Description: <input type="text" id="item_description" placeholder="Enter a description..."/> </br>
Item Image(link): <input type="text" id="item_image" placeholder="Enter a image link..."/> </br>
rsid: <input type="text" id="rs_item_id" placeholder="Enter a item id..."/> </br>
rsam: <input type="text" id="rs_item_amount" placeholder="Enter a item amount..."/> </br>
<button id="update">Update item</button>
<script>
    var name    = document.getElementById("item_name");
    var price   = document.getElementById("item_price");
    var desc    = document.getElementById("item_description");
    var img     = document.getElementById("item_image");
    var rsid    = document.getElementById("rs_item_id");
    var rsam    = document.getElementById("rs_item_amount");
    var button  = document.getElementById("update");
    button.addEventListener("click", function() {
        alert("Name = " + name.value + "\n" 
            + "Price = " + price.value + "\n" 
            + "Desc = " + desc.value + "\n" 
            + "Img = " + img.value + "\n" 
            + "rsid = " + rsid.value + "\n" 
            + "rsam = " + rsam.value + "\n");
    });
</script>

2 个答案:

答案 0 :(得分:1)

问题在于,因为你将它们全部变为全局变量,name一个与window.name属性冲突。

使用不同的变量名称,或创建闭包将起作用

答案 1 :(得分:0)

name, price, desc, img, rsid, rsam置于事件处理程序中。

var button  = document.getElementById("update");

button.addEventListener("click", function() {
  var name    = document.getElementById("item_name");
  var price   = document.getElementById("item_price");
  var desc    = document.getElementById("item_description");
  var img     = document.getElementById("item_image");
  var rsid    = document.getElementById("rs_item_id");
  var rsam    = document.getElementById("rs_item_amount");


    alert("Name = " + name.value + "\n" 
        + "Price = " + price.value + "\n" 
        + "Desc = " + desc.value + "\n" 
        + "Img = " + img.value + "\n" 
        + "rsid = " + rsid.value + "\n" 
        + "rsam = " + rsam.value + "\n");
});

演示:http://jsbin.com/fivos/1/edit?html,output