获取子图像的src

get src of child Image

本文关键字:src 图像 获取      更新时间:2023-09-26

我在a标记中有一个img标记。如果我悬停在a标签上,那么我想提醒src img标签,并删除它的最后4个字符。

HTML:

<a onmouseover="hoverImage($(this))">
    <img src="https://www.google.de/images/srpr/logo11w.png" height="24" alt="" title="" />
    <p>Startseite</p>
</a>

JavaScript:

function hoverImage (e) {
 alert(e.find('img').getAttribute('src'));
}

我尽力了,但没有成功:(

http://jsfiddle.net/opvryy00/

尝试这个

HTML

<a >
    <img src="https://www.google.de/images/srpr/logo11w.png" height="24" alt="" title="" />
    <p>Startseite</p>
</a>

JS-

$( "a" ).mouseover(function() {
   var src=$(this).find("img").prop('src');
    src=src.slice(0,-4);
    alert(src)
});

jsfiddle

不要使用内联JavaScript:它非常丑陋和过时,因为你可以使用脚本做你想做的一切。

删除HTML中的onmouseover="..."属性,在链接中添加一个id,然后使用Javascript来监听事件,如下所示:

HTML:

<a id="my-link">
    <img src="https://www.google.de/images/srpr/logo11w.png" height="24" alt="" title="" />
    <p>Startseite</p>
</a>

Javascript:

function hoverImage(e) {
    var img = $(e.target).find('img');
    alert(img.getAttribute('src'));
    // Delete the last 4 characters
    img.setAttribute('src', el.getAttribute('src').slice(0, -4));
}
$("#my-link").mouseover(hoverImage);

试试这个:

$('a').mouseover(function(){
    alert($(this).find('img').attr('src').slice(0, -4));
});

这里试试这个代码。您可以删除标记中的onmouseover属性。

HTML

<a>
  <img src="https://www.google.de/images/srpr/logo11w.png" height="24" alt="" title="" />
  <p>Startseite</p>
</a>

JS

$(function()
{
  $('a').mouseover(function(){
     var str = $(this).find('img').attr('src');             
      var new_str = str.substring(0,str.length - 4);
      alert(new_str);
  });      
});

我建议您稍微调整一下您的方法,让我们删除内联javascript并直接针对图像。此外,让我们避免警报,你可以看到结果显示在你的锚下。

HTML

<a>
    <img src="https://www.google.de/images/srpr/logo11w.png" height="24" alt="" title="" />
    <p>Startseite</p>
</a>
<div class="output"></div>

JS

var hoverImage = function(e) {
    var $img = $(e.currentTarget),
        src = $img.attr('src'),
        newSource;
    newSource = src.substring(0, src.length - 4);
    $('.output').html(newSource);
}
$(document).on('ready', function() {
    $('img').hover(hoverImage);
});

http://jsfiddle.net/_naz/u2f2qeaw/