未捕获的类型错误:无法读取属性,JS 在页面呈现之前执行

Uncaught Type Error: Cannot read property, JS executing before page renders

本文关键字:JS 执行 属性 类型 错误 读取      更新时间:2023-09-26

我在控制台中收到以下错误:

Uncaught TypeError: Cannot read property ‘value’ of null

我正在尝试做的是将文本输入从一个输入框复制到另一个输入框中,当您单击该复选框时,一个输入的值将被复制到另一个输入中。

.HTML

<input name="stry" type="text" id="stry"/> 
<input type="checkbox" name="sendsms" onclick="CopyStory(this.form)">
<div id="container">
<input type="text" class="form-control" name="body">
</div>

.JS

function CopyStory(f) {
  if(f.sendsms.checked == true) {
    f.stry.value = f.body.value;
  }
}  

我相信问题是代码是在元素加载之前执行的,因为我有一个 javascript 警报模式弹出窗口,除非您按"确定",否则它会阻止页面加载

警报 JS

$('#container').fadeOut('fast').delay(7000).fadeIn('fast');
alert("This page is loading....");

我试过把它包装在document.ready(函数等等...但随后它给了我一个错误:"'CopyStory'未定义"。

有什么建议吗?

看看这个JSFiddle。

.JS

function copyStory(ch) {
                if(ch.checked)
                var text1 = document.getElementById("stry").value;
                else
                text1='';
                document.getElementById("second").value = text1;             
                }
$('#container').fadeOut('fast').delay(7000).fadeIn('fast');
alert("This page is loading....");   

.HTML

<input name="stry" type="text" id="stry"/> 
<input type="checkbox" name="sendsms" onclick="copyStory(this)">
        <input type="text" class="form-control" id="second" name="body">
<div id="container">
</div>

您没有使用 form 标签并尝试访问表单..!

试试这个,

function CopyStory(f) {
  if(f.sendsms.checked == true) {
      console.log(f.body.value);
    f.stry.value = f.body.value;
  }
}  
<div>
<form>
<input name="stry" type="text" id="stry"/> 
<input type="checkbox" name="sendsms" onclick="CopyStory(this.form)">
<div id="container">
<input type="text" class="form-control" name="body">
</form>
</div>

只需将 js 脚本放在<head></head>

首先,将代码包装在$(function(){ //code here });中,以便在页面加载后执行 js。

关于'CopyStory' is not defined :当您定义函数时,例如:

$(function(){
   function CopyStory(){ //... }
});

CopyStory在全局范围内不可见,因此,如果您想解决问题,只需将定义更改为:

$(function(){
    window.CopyStory = function(){ //... }
});

附言将变量分配给window属性是在局部范围内定义全局变量的唯一方法。