动态扭曲锚标签内的图像[jQuery]

时间:2017-06-29 05:24:55

标签: javascript jquery html ajax

我有这样的表数据:

<td id="tinkerDiv1">
    <a id="slugTinker1"><img id="imageTinker"></a>
</td>

我正在尝试使用ajax更改图像和锚点链接。关于ajax的成功功能我有:

success: function(data) {
            console.log('Id:' +data.post.id);
            //var imgname = data.post.image;
            var image = "{{ asset('/frontend/img/uploads/') .'/' }}" + data.post.image;
            var img = $('<img id="imageTinker" class="img-responsive animation-fadeInQuick" style="width:175px;">');
            img.attr('src', image);

            img.appendTo('#tinkerDiv1');
            var slug = "{{ url('/post/') .'/' }}" + data.post.slug;
            var sluglink1 = $('#slugTinker1');
            sluglink1.attr('href', slug);
}

预期输出:

<a id="sluglink1" href="someurl.html">
    <img id="imageTinker" class="img-responsive animation-fadeInQuick" style="width:175px;" src="someimage.jpg">
</a>

但我得到的是这样的东西:

<a id="sluglink1" href="someurl.html"></a>
<img id="imageTinker" class="img-responsive animation-fadeInQuick" style="width:175px;" src="someimage.jpg">

问题:锚标记未包装Image标记。

3 个答案:

答案 0 :(得分:3)

问题在于img.appendTo('#tinkerDiv1'); tinkerDiv1是td的ID。

将其替换为

$("#sluglink1").append(img)

答案 1 :(得分:2)

请检查以下代码。它会对你有所帮助。

success: function(data) {
            console.log('Id:' +data.post.id);
            //var imgname = data.post.image;
            var image = "{{ asset('/frontend/img/uploads/') .'/' }}" + data.post.image;
            var img = $('<img id="imageTinker" class="img-responsive animation-fadeInQuick" style="width:175px;">');
            img.attr('src', image);

            var slug = "{{ url('/post/') .'/' }}" + data.post.slug;
            var sluglink1 = $('#slugTinker1');
            sluglink1.attr('href', slug);
            sluglink1.html(img);
            sluglink1.appendTo('#tinkerDiv1');
}

答案 2 :(得分:1)

你要附加div,你必须这样做

img.appendTo('#slugTinker1');