src / background-url /?

时间:2011-09-12 06:17:35

标签: jquery css

因为我必须创建一个可以改变图像的功能(src / background-url)。我想知道如何识别标签&是否使用src或url访问图像 让我们说

<div class="parent">
  <input type="button" class="change" style="background-image:url('image1.jpg')" />
  <img class="change" src="/image2.gif" />
</div>

之前我写了一个fn,可以更改背景图片网址,但是这个fn无法替换&lt; img> src

$(function(){
   $('.change').click(function(){ 
       var url = getUrl_by_Ajax() /* this fn returns the file path */
       $(this).css('background',url); /* it can only change the background image not img src*/
    /* following line can change the src if this function knows already whether it's  
       src/url  */
     $(this).attr('src', url);
  });
});

我的问题是:

  1. 如何动态了解选择器的标签及其css for image
  2. 访问图片的方式有多少,例如按钮使用url&amp; img使用src。

    <input type="button" background-img: url('...'); />
    <img src= "...." />

    ? ?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$(function(){
   $('.change').click(function(){ 
       var url = getUrl_by_Ajax() /* this fn returns the file path */
       if ($(this).is('img'))
           $(this).attr('src', url);
       else
           $(this).css('background', url);
  });
});