0

I'm trying to extract the src of an img and then paste the src into a "a href" to wrap around the original img

I have two versions that I've messed with and can't get either to work. I think one of my problems seems to be inserting an "a href" before or around an element.

<script type="text/javascript">
  var x = hdnImg.children('img').attr('src') 

  $( "img" ).wrap(function() {
  return "<a href='" +x+ "' class="anyclass"></a>";
    });
</script>

or

<script type="text/javascript">
  var p = hdnImg.children('img').attr('src')

  $( "img" ).before( "<a href='#' class="anyclass">" );
  $( "img" ).after( "</a>" );
</script>

ultimately, this is was I'm trying to go for:

html before script:

    <img src="http://a.jpg">
    <img src="http://b.jpg">

html after script

    <a hre="http://a.jpg" class="classy"><img src="http://a.jpg"></a>
    <a hre="http://b.jpg" class="classy"><img src="http://b.jpg"></a>

I'm still learning javascript and could use a little guidance. Thanks

4

5 回答 5

1
$('img').each(function(index,ele) {
    $(this).wrap('<a href="' + $(ele).attr('src') + '" class="classy"></a>');
});

http://jsfiddle.net/AWeAu/

于 2013-09-17T18:01:27.443 回答
1

尝试使用

$( "img" ).each(function() {
    var x = $(this).attr('src'); 
    $(this).wrap( "<a href='" +x+ "' class='anyclass'></a>");
});
于 2013-09-17T17:50:13.943 回答
0

试试这个,这对你有帮助

HTML

 <img src="http://a.jpg">
    <img src="http://b.jpg">
        <div></div>
        <input type='button' value='Click Me'/>

JS

$('input[type=button]').click(function(){
    $('img').each(function(){
        var item='New: <a href='+$(this).prop('src')+' class="classy"><img src='+$(this).prop('src')+' ></a>';
    $(this).remove();
    $('div').append(item);
    });
});

小提琴Here

于 2013-09-17T17:56:06.433 回答
0
<div class="images">
   <span><img src="http://a.jpg"></span>
   <span><img src="http://b.jpg"></span>
</div>

使用以下脚本:

 $(document).ready(function () {
        $('.images img').each(function () {

            var link = "<a href='" + $(this).attr("src") + "'>" + $(this).closest('span').html() + "</a>";
            $(this).closest('span').html(link);
        });
    });
于 2013-09-17T17:56:10.323 回答
0

也许这可以帮助你。

$("img").addClass("classy");
$("img").html('<img src="http://b.jpg">');
于 2013-09-17T17:50:00.147 回答