2013-01-15 56 views
0

IFRAME SRC改变我目前有一些JavaScript,看起来有点像这样:与JavaScript不工作

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
function changeSource(newSource) { 
    document.getElementById('preview').src = newSource; 
} 
}); 
</script> 

然后,我有一些HTML,看起来像这样:

<table border=0 class="colors"> 
    <tbody> 
    <tr> 
     <td><a onclick="changeSource('http://www.test.com')"><img width="40" src="test.png"/></a></td> 
    </tr> 
    </tbody> 
</table> 

随后的iFrame部分:

<table border=0> 
    <tbody> 
    <tr> 
     <td><iframe id="preview" width="125" height="303" src="test.php" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe></td> 
    </tr> 
    </tbody> 
</table> 

但是点击标签中的图片iframe的来源不会改变。这是为什么?

回答

1

由于函数是一个本地方法,因为您将它隐藏在了onready函数中,所以出现错误。这个例子中没有必要使用onready调用。

必须

<script> 
    function changeSource(newSource) { 
     document.getElementById('preview').src = newSource; 
    } 
</script> 

更妙的是,无需JavaScript的!使用HTML就像它应该被使用。使用目标属性。

<td><a href="http://www.example.com" target="preview"><img width="40" src="test.png"/></a></td> 
+0

工作完美,非常感谢。一旦时间用完,我会接受你的答案。 – user1981730

0

您正在使用jquery。最好做一个完美的使用。

 
$(document).ready(function(){ 
    // selecting anchor tag for table with class colors 
    $("table.colors a").click(function(e){ 
     e.preventDefault(); 
     var newSource = $(this).attr("href"); 
     $("#preview").attr({"src" : newSource}); 
    }); 
}); 

无需加入的onclick属性或目标属性与HTML搞乱的。 但html的目标属性是最优选的。

<table border=0 class="colors"> 
    <tbody> 
    <tr> 
     <td><a href="http://www.test.com"><img width="40" src="test.png"/></a></td> 
    </tr> 
    </tbody> 
</table>