从Div获取图像文件名,并将其复制到悬停按钮上的文本字段中

Get image file name from Div and copy into text field on button hover

本文关键字:按钮 悬停 字段 文本 复制 图像 获取 Div 文件名      更新时间:2023-09-26

在id为#prlogo的div中,我有一个图像。当我将鼠标悬停在带有id#按钮的按钮上时,我需要将服务器上图像的文件名或位置复制到带有id#input_2_16的文本文件中。

听起来很简单,但我一直在努力做到这一点。。。

Div html:

<div id="prlogo" class="prlogo"><img class="logoplace" src="../preview/logo-place.png"/>
        </div>

Miro

没有更多上下文并使用jQuery。

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() { //this anonymous function will run when the page is ready
    $("#button").hover(function() {
      //mouse enter
      var imgSrc = $("#prlogo img").attr("src"); 
      //assumes there is an <img /> tag as a child of the #prlogo div
      $("#input_2_16").val(imgSrc);
    },function() {
      //mouse leave
    });
});
</script>

如果你不想在鼠标离开时做任何事情,你可以做

$("#button").mouseenter(function() {
  //mouse enter
  var imgSrc = $("#prlogo img").attr("src"); 
  //assumes there is an <img /> tag as a child of the #prlogo div
  $("#input_2_16").val(imgSrc);
});

如果我读对了,它会是这样的:

$( function () {
    $( '#button' ).mouseover( function () {
        var src = $( '#prlogo img' ).attr( 'src' );
        $( '#input_2_16' ).val( src );
    } );
} );
​

如果您需要在DOM中向下遍历多个级别,请使用.find代替.children.

$('#button').on('hover', function(){
        $('#input_2_16').val($('#prlogo').children('img').attr('src'));
});