Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在jQuery attr(';src';value)中将图像id用作源?_Jquery - Fatal编程技术网

如何在jQuery attr(';src';value)中将图像id用作源?

如何在jQuery attr(';src';value)中将图像id用作源?,jquery,Jquery,我在Jquery代码中遇到了一个问题。请帮我解决这个问题 用于显示图像的HTML代码: <body> <div class="info_image">image1</div> <div class="info_image">image2</div> <div class="info_image">image3</div> 请帮助我修复此jquery代码。使用.each()在Div上迭代。

我在Jquery代码中遇到了一个问题。请帮我解决这个问题

用于显示图像的HTML代码:

<body>
    <div class="info_image">image1</div>
    <div class="info_image">image2</div>
    <div class="info_image">image3</div>
请帮助我修复此jquery代码。

使用
.each()
在Div上迭代。获取html

并使用
.css()
设置相应的背景图像

$('.info_image').each(function() {
    var $this = $(this);  
    var imgId = $this.html(); // Assuming the div html contains just the image ID
    var imgSrc = $('#' + imgId).attr('src');

    $this.css('backgroundImage','url('+ imgSrc + ')');
})
最好使用HTML5数据属性来存储图像ID,而不是html,因为您可能需要处理空格或其他字符的情况

<div class="info_image" data-image="image1">Here comes image1</div>
<div class="info_image" data-image="image2">Here comes image2</div>
<div class="info_image" data-image="image3">Here comes image3</div>

这会更干净

你想把这些图像放在div标签中吗?你说的“不工作”是什么意思?是否有错误?是否要在包含文本image1的div中显示id=“image1”的图像?
$('.info_image').each(function() {
    var $this = $(this);  
    var imgId = $this.html(); // Assuming the div html contains just the image ID
    var imgSrc = $('#' + imgId).attr('src');

    $this.css('backgroundImage','url('+ imgSrc + ')');
})
<div class="info_image" data-image="image1">Here comes image1</div>
<div class="info_image" data-image="image2">Here comes image2</div>
<div class="info_image" data-image="image3">Here comes image3</div>
  $('.info_image').each(function() {
            var $this = $(this);  
            var imgId = $this.data('image'); 
            var imgSrc = $('#' + imgId).attr('src');

            $this.css('backgroundImage','url('+ imgSrc + ')');
        })