2010-04-08 64 views
1

我有JavaScript代码,其中复制输入文件的值,并在文本框中实时过去。为什么JavaScript IF只能使用一次?

<script> 
function copyit(){ 

var thephoto=document.getElementById('thephoto').value; 
var fileonchange=document.getElementById('fileonchange').value; 

if(!thephoto==fileonchange){ 
document.getElementById('fileonchange').value=thephoto; 
} 

} 

window.setInterval("copyit()", 500); 
</script> 

Choose File : <input type="file" id="thephoto"><br> 
Here Is the file name : <input type="text" id="fileonchange"> 

不幸的是,这只能用一次,然后再次更改文件时停止粘贴值。 (我的意思是你应该重新加载页面再次运作)

IF有一个缓存或什么?你可以自己试试看代码。

谢谢大家

回答

8

语法错误。您需要!=运营商表示不平等:

if (thephoto != fileonchange) { 

!thephoto实际上逆其布尔表示(即true变得false,反之亦然,也null变得true)。 ==实际上比较了两个操作数的相等性。

+0

谢谢你这么多BalusC,你知道,女孩吮吸代码XD – Emily 2010-04-08 18:39:10

+0

亲爱的,那不是与性别:)只要有好书/教程,动机和心态。快乐的编码。 – BalusC 2010-04-08 18:55:42

0

严格不平等使用!==

或者,如果你想使用类似你写的语法什么的,做到这一点:

if(!(thephoto==fileonchange)){

1

BalusC是完全正确的,但恕我直言,使用计时器每500ms做这个简单的任务似乎很重。

你为什么不干脆用onchange事件<input type="file" />的?,例如:

window.onload = function() { 
    var thephoto = document.getElementById('thephoto'); 
    var fileonchange = document.getElementById('fileonchange'); 

    thephoto.onchange = function() { 
    // this function will be executed when the user changes the file 
    fileonchange.value = this.value; 
    }; 
}; 

检查上面的例子here

+0

CMS,Onchange不能正常工作,即你应该点击页面中的某处来激活粘贴值:( – Emily 2010-04-08 18:40:24

1

正如W3C所说,输入元素接受onchange方法。你为什么不这样做:

<input type="file" id="thephoto" onchange="copyit()"> 

而不是使用可怕的setInterval?

2

尝试更改IF行:

if(thephoto!=fileonchange){ 
相关问题