2013-01-20 33 views
1

使用jQuery,我想更改懸停時的src屬性。例如,我有以下HTML:jQuery從圖像src屬性中刪除文本

<img src="convert.php?image=images/example.jpg" alt="#" /> 

在懸停時,我想刪除「convert.php?」字符串以便HTML是:

<img src="image=images/example.jpg" alt="#" /> 

必須很簡單嗎?

回答

2

回答了自己的問題。找到這個片段。

$('.item img').each(function(e){ 
    var src = $(this).attr('src'); 
    $(this).hover(function(){ 
     $(this).attr('src', src.replace('convert.php?image=', '')); 
    }, function(){ 
    $(this).attr('src', src); 
    }); 
    }); 
+0

除了不重新就像問題中給出的例子一樣,但我期望這就是你的意思。 – Popnoodles

-1
$("img").hover(
     function() { 
     var src = $(this).attr('src'); 
     jQuery.data(this, 'old_source', src); 
     srcNew = src.replace("convert.php?", ""); 
     $(this).attr('src', srcNew); 
     $(this)., srcNew); 
     }, 
     function() { 
     var src = $(this).data('old_source'); 
     $(this).attr('src', src); 
     } 
    ); 
+0

將不起作用,因爲'src'在第二個處理程序中未定義,它只在第一個處理程序中有作用域 – charlietfl

0

可以使用attr(function(){}

下面將恢復圖像mouseleave以及

$(".item img").hover(function() { 
     var convert='convert.php?image='; 
    $(this).attr('src',function(idx, attr){ 
      return attr.indexOf(convert) <0 ? convert+attr : attr.replace(convert,''); 
    }); 
}); 

當作爲參數傳遞只有一個功能徘徊它能向兩家mouseentermouseleave事件運行