Javascript变量未定义,onchange不起作用

Javascript Variable undefined and onchange not working

本文关键字:onchange 不起作用 未定义 变量 Javascript      更新时间:2023-09-26

我是Javascript的初学者,所以这对专家来说可能很容易解决。我正在努力:http://www.3dsbuzz.com/receng/test.php源代码如下。

其想法是将图像拖动到白框中,为文本框添加一个值,然后触发mysql查询并显示一些数据。但我有两个问题:

1) 当将图像拖动到白色框中时,它不会显示图像的值属性,而是显示"未定义"。

2) 当我硬编码一个值而不是使用变量(在第17行)时,它会很好地进入文本框,但不会触发mysql查询,尽管如果您直接在框中键入它,它会触发。

<html>
<head>
<style type="text/css">
#div1 {width:175px;height:97px;border:1px solid #aaaaaa;}
</style>
<script type="text/javascript">
function drag(ev){
    ev.dataTransfer.setData("Text",ev.target.id);
}
function allowDrop(ev){
    ev.preventDefault();
}
function drop(ev){
    ev.preventDefault();
    ev.target.appendChild(document.getElementById(ev.dataTransfer.getData("Text")));
    var newtext = document.dragme.value;
    document.myform.users.value += newtext;
}
function showUser(str){
if (str==""){
  document.getElementById("txtHint").innerHTML="";
  return;
  }
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="myform">
<input type="text" name="users" onchange="showUser(this.value)">
</form>
<div id="txtHint"><b>Type "49" or "50" in the box above</b></div>
<br>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br />
<img id="49" name="dragme" value="49" src="http://www.3dsbuzz.com/wp-content/uploads/2012/06/mutantmuddsthumb.jpg" draggable="true" ondragstart="drag(event)" />
<img id="50" name="dragme" value="50" src="http://www.3dsbuzz.com/wp-content/uploads/2011/09/layton-thumb.jpg" draggable="true" ondragstart="drag(event)" />
</body>
</html>  

1)图像没有固有的value属性。要么必须使用getAttribute作为值,要么,由于id和值相同,只需获取丢弃图像的id:

function drop(ev){
    ev.preventDefault();
    ev.target.appendChild(document.getElementById(ev.dataTransfer.getData("Text")));
    var newtext = ev.dataTransfer.getData("Text");
    document.myform.users.value += newtext;
}

2) 只有当用户更改值时,才会调用更改处理程序,而不是当脚本更改值时。你必须手动触发它:

showUser(newtext);

不应该

var newtext = document.draging.value;

var newtext = document.dragimg.value;

因为拖动没有定义。