【发布时间】:2016-06-06 19:29:43
【问题描述】:
我有一个包含用户帖子的论坛页面。我需要创建一个回复文本区域,用户可以在其中回复任何帖子。问题是每当回复帖子时,我的 JS 脚本都无法检测到回复所属的特定帖子。
这是生成帖子列表并创建回复表单的 php sn-p。
echo'
<div id="div'.$post_id.'"></div>
<form name="form'.$post_id.'">'; echo'
<div class="row">
<div class="col-sm-1">
<img src="" width="70" height="70" class="img img-responsive" alt="Your profile picture.">
</div>
<div class="col-sm-4">
<textarea placeholder="Your reply" name="user_reply" class="form-control" maxlength="250" rows="3" required></textarea>
<input type="hidden" name="user_id" value="'.$userId .'">
<input type="hidden" name="time" value="'.$time .'">
<input type="hidden" name="date" value="'.$date .'">
</div>
<div class="col-sm-1">
<button name="data" type="button" onclick="sendReply(\' '.$post_id.' \');">Reply</button>
</div>
</div>
</form>
</div>';
现在这是我认为应该选择用户回复并将值发送到reply.php文件的JS脚本
<script>
function sendReply(id){
x='document.form'+id;
post_id = id;
user_id = x.user_id.value;
reply = x.user_reply.value;
date = x.date.value;
time = x.time.value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("div"+id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'reply.php?reply='+reply+'&post_id='+post_id+'&user_id='+user_id+'&time='+time+'&date='+date, true);
xmlhttp.send();
}
</script>
最后是我在点击回复按钮时在浏览器控制台中遇到的错误
(index):121 Uncaught TypeError: Cannot read property 'value' of undefinedsendReply
@ (index):121onclick
@ VM161:211
【问题讨论】:
-
我认为您绝对应该查看一些已经存在的优秀教程。喜欢this one。关于您的问题,它说它无法读取未定义的属性“值”。原因是因为
x='document.form'+id;其中 x 计算为简单字符串 - 所以 x.user_id 不存在,x.user_id.value 也不存在。你想要的是从页面获取表单然后访问它元素。您可以使用 x = document.forms; 获取所有表单的列表
标签: javascript html forms dom