我知道这是非常基本的,但我几乎没有编码经验,还没有找到为什么这个函数总是返回未定义的,请帮助。
<script>
function myFunction() {
var x,y;
y = document.getElementById("nent_nonce");
z = document.getElementById("next_server_seed_hash");
}
</script>
我使用的新代码我取出了脚本,因为它不断给我和意外的令牌<我打算稍后修复>我打算稍后修复>
function x() {
return [ $('#next_nonce').html(), $('#next_server_seed_hash').html() ]
}
这就是给我未定义的原因,尽管尝试任一 document.getelementbyid 有效
JavaScript 函数返回undefined
,除非你明确return
某些内容。考虑:
function x() {
5;
}
当你打电话给x()
你会得到undefined
.
相反:
function x() {
return 5;
}
如果你没有一个好的JavaScript参考,如果没有一个,你就不会走得很远。好消息是 Mozilla 有很棒的文档来帮助你入门。
返回两个元素的一种解决方案是使用数组,如下所示:
function x() {
return [
$('#next_nonce').html(),
$('#next_server_seed_hash').html()
];
}
或者你可以返回一个 JavaScript 对象:
function x() {
return {
next_nonce: $('#next_nonce').html(),
next_server_seed_hash: $('#next_server_seed_hash').html()
};
}
使用html()
意味着这些是包含内容的标准HTML元素,例如<div>
或<p>
。如果这些是表单元素,则应使用 val()
来获取标记中的 value="..."
属性。