Javascript/HTML错误“属性”selectReason“的值为null或未定义,而不是函数对象

Javascript/HTML error “the value of the property “selectReason” is null or undefined, not a function object

本文关键字:未定义 null 对象 函数 的值为 错误 HTML 属性 selectReason Javascript      更新时间:2023-09-26

嗨,我是javascript和html的新手,想知道是否有人能帮助我理解为什么这个错误不断发生。基本的想法是,我有一个下拉列表,其中填充了几个选项。当客户选择一个选项时,会触发onchange事件,将所选选项的值写入文本区域。然而,当我调试它时,我收到了上面的消息,我在下面包含了相关的代码片段:

function selectReason() {
    var selectindex = document.getElementById("selectmessage").selectedIndex;    
    var selecttext = document.getElementById("selectmessage").value;
    document.getElementById("Txt").value = selecttxt;
}
<TR style="DISPLAY: none; VISIBILITY: hidden" id=sel>
    <TD width="60%" align=left>Please select a reason</TD>
    <TD width="40%" align=left>
        <SELECT id="selectmessage" onchange="selectReason()" style="WIDTH: 425px"></SELECT>
    </TD>
</TR>

您可能缺少<table>标记,因为这给我带来了问题。您提供的代码段也有var selecttextdocument.getElementById("Txt").value = selecttxt;<-缺少一个e.

下面提供的代码片段对我很有用。可能只是未能关闭函数/html中的某个标记。

此外(这可能是你添加内联以提供更好的图片),你应该避免内联样式和(对我来说)函数。包括一个.css和.js文件。

function selectReason() {
  var selectindex = document.getElementById("selectmessage").selectedIndex;   
  var selecttext = document.getElementById("selectmessage").value;
  var elem = document.getElementById("hey");
  elem.innerHTML = selecttext;
}
// Events to attach
function init () {
  var elem = document.getElementById('selectmessage');
  elem.addEventListener('change', selectReason)
 }
// Run 'init' when the DOM is ready (jQuery's $(document).ready() )
document.addEventListener("DOMContentLoaded", init, false);
<table>
<TR>
<TD>Please select a reason</TD>
<TD>
  <SELECT id="selectmessage">
  <option>Hello</option>
  <option>Yes</option>
  </SELECT>
</TD>
</TR>
<tr>
    <td id='hey'></td>
 </tr>
  </table>

也许这可以帮助您

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
    <table>
        <tbody>
            <tr>
                <td>
                    <select name="" id="selectmessage">
                        <option value="red">red</option>
                        <option value="gree">green</option>
                        <option value="blue">blue</option>
                    </select>
                </td>
            </tr>
        </tbody>
    </table>
    <textarea name="" id="txt" cols="30" rows="10">

    </textarea>
    <script type="text/javascript">
        $(document).on('ready', function(){
            $('#selectmessage').on('change', function(){
                var val = $(this).val();
                var txt = $('#txt');
                    txt.val(val);
            });
        });
    </script>
</body>
</html>

希望:)