Iframe src改变与Javascript不工作

Iframe src change with Javascript not working

本文关键字:工作 Javascript src 改变 Iframe      更新时间:2023-09-26

我目前有一些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的源不会改变。为什么会这样?

你得到一个错误,因为函数是一个本地方法,因为你隐藏在onready函数。该示例不需要onready调用。

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

必须是

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

更好的是,不需要JavaScript !按照应该使用的方式使用HTML。使用target属性

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

您正在使用jquery。

<>之前$(文档)时函数(){//为带有类颜色的表选择锚标记$("表。颜色").click(函数(e) {e.preventDefault ();var newSource = $(this).attr("href");$(" #预览")。attr({"src": newSource});});});之前不需要通过添加onclick属性或target属性来混淆html。但是html的target属性是最好的。
<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>