【问题标题】:Alerting an object() value that is gotten from an input using JavaScript使用 JavaScript 警告从输入中获取的 object() 值
【发布时间】:2014-01-16 08:31:31
【问题描述】:

我正在尝试使用输入元素获取对象值,但它不起作用,这是我尝试过的

    var operator = new Object();
    operator.name = document.getElementById("name").value;
    operator.country = document.getElementById("country").value;
    operator.occupation = document.getElementById("occupation").value;
    operator.status = document.getElementById("status").value;
    alert(operator.name + operator.country + operator.occupation + operator.status);

它一直在提醒 undefined。

       <form action="process.php" method="post" onsubmit="return myValidate()" name="myform">

姓名:



  

国家:



  

职业:



  

状态:



【问题讨论】:

  • 控制台出现什么错误? ..但它不起作用
  • 不工作意味着什么?

标签: javascript html forms object


【解决方案1】:

尝试使用代表对象源代码的toSource() 方法。它将返回对象属性及其值

alert(operator.toSource());

这是一个例子Fiddle

编辑:

toSource() 在 Internet Explorer 或 Safari 中不起作用。这不是一个好习惯。所以你可以使用

alert(operator.name.toString());

【讨论】:

  • .toSource() 是什么?你在说.toString()
  • @Pilot 返回对象值
  • Is .toSource() 仅用于函数对象。我得到uncaught TypeError: Object #&lt;Object&gt; has no method 'toSource'
  • .toSource() 此功能是非标准的,不在标准轨道上。不要在面向 Web 的生产站点上使用它:它不适用于每个用户。实现之间也可能存在很大的不兼容性,并且行为可能会在未来发生变化。*
【解决方案2】:

我刚刚试了一下http://jsfiddle.net/47LRJ/,它运行良好。你能显示你的 HTML

<form>
    <input id="text" type="text" value="text" />
</form>

var obj = new Object();
obj.text =  document.getElementById("text").value;
alert(obj.text);

【讨论】:

  • 这看起来和我的很像
【解决方案3】:

我猜你在表单被填满值之前会发出警报(我们可能需要查看表单 html 代码)

此代码是否在文档加载时调用?

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 2021-06-14
    • 2013-07-28
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多