脚本来读取图像src

时间:2012-11-14 08:47:13

标签: javascript

我是脚本编写的新手,并且花了很多时间来编写代码。

我想读取某些图像的动态书写来源,然后在页面下方写下另一张图像,其源代码略有不同,如

此图片动态写在页面顶部的页面上

<img src="chrome.jpg" id="test1"> 

然后降低我想写 -

<img src="chrome2.jpg">

非常感谢amy对此的帮助。

2 个答案:

答案 0 :(得分:0)

假设带有'page',你引用了html页面......我进一步假设你想在客户端这样做......

你需要使用javascript,使用javascript库来完成这样的任务是有道理的,事情会变得更容易。例如,使用jQuery库,您可以使用“选择器”来识别和使用dom树元素,并添加或更改所需的所有内容。类似的东西:

source=$('img#test1').attr('src');
// do something with the source url contained now inside source
$('p#further_down').append('<img>).attr('src',source);

<html>
<head>  

  <!-- inclusion of the jQuery Javascript library -->
  <script 
    type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
  </script>

  <!-- this is 'your' function -->
  <script type="text/javascript">
    function doubleImg(){
      // you 'get' the source url of the upper image:
      var topSrc=$('#top img').attr('src');
      // no you can do something with that url
      // for this demo I replace the 'direction' inside the icons name: 
      var bottomSrc=topSrc.replace(/up/, 'down');
      // now you create a new <img> tag 
      // and 'set' the changed url as 'src' attribute:
      var img=$('<img width="100">').attr('src',bottomSrc);
      // and finally you 'add' that <img> tag into your dom tree ("the page"): 
      $('#bottom').append(img);
    }
  </script>

  <!-- this gets 'your' function executed ->
  <script type="text/javascript">
    $(window).load(doubleImg);
  </script>
</head>

<body>
  <!-- the "top" frame, note that it DOES hold an <img> inside -->
  <fieldset id="top" style="border=2px solid green;">
    <legend>TOP</legend>
    <img width="100" src="http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/128/Actions-arrow-up-icon.png">
  </fieldset>
  <br>
  <!-- the "bottom" frame, note that it DOES NOT hold an <img> inside -->
  <fieldset id="bottom" style="border=2px solid blue;">
    <legend>BOTTOM</legend>
  </fieldset>
</body>
</html>

答案 1 :(得分:0)

我不确定你的脚本是什么意思,所以我提供了两种方法来实现你的愿望,通过DOM&amp;通过jQuery

  • Using jQuery:

检索图像的`src:

var src = $(“#test1”).attr('src');

更改图片的src

$("# test1").attr("src","chrome2.jpg");
  • Using DOM:

检索图像的`src:

document.getElementById("test1").src;

更改图片的src

document.getElementById("test1").src="chrome2.jpg";

希望它有所帮助。