gpt4 book ai didi

Javascript document.getElementById(arg) - 对象为 null 或未定义

转载 作者:行者123 更新时间:2023-11-28 21:15:43 25 4
gpt4 key购买 nike

我有一个设置 selected = true 的函数。我有一个国家/地区的下拉列表。每个选项都有 ID,例如 USA、GER...

    function nation(arg) 
{
if (arg == '<?php echo $this->escape($this->user->get( 'country' ));?>')
document.getElementById(arg).selected = true;
}

window.onload = nation('<?php echo $this->escape($this->user->get( 'country' ));?>');

我确信 php 代码会返回正确的国家/地区,但 javascript 调试器会说:

SCRIPT5007: Unable to set value of the property 'selected': object is null or undefined 

这里有什么问题吗?

最佳答案

您正在调用nation 立即,然后将其返回值分配给 onload ,所以你几乎肯定是在 <select> 之前调用它。已添加到 DOM。

您需要分配一个函数。

window.onload = function () {
nation('<?php echo $this->escape($this->user->get( 'country' ));?>');
};

关于Javascript document.getElementById(arg) - 对象为 null 或未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com