开发者

How get a variable from div in HTML

开发者 https://www.devze.com 2023-03-10 14:44 出处:网络
I have the following div\'s in HTML that look like this: <div id=\"data\"> <div class=\"img\"><img src=\"imageurl_1\"></div>

I have the following div's in HTML that look like this:

<div id="data">
  <div class="img"><img src="imageurl_1"></div>
  <div class="img"><img src="imageurl_2"></div>
  <div class="img开发者_StackOverflow"><img src="imageurl_3"></div>
  <div class="img"><img src="imageurl_4"></div>
</div>

What is the best way to extract the image src's into a variable before sending it via POST?


var src_url = $('img').attr('src');


Something like this?

var urls = '';
$('div.img > img').each(function(i) {
       urls = urls + ' ' + $(this).attr('src');
});
alert(urls);  // should contain all urls

working jsfiddle: http://jsfiddle.net/gfosco/bWZKp/


All of them at once for any in div.img? Not sure how you want it formatted, but you can access the value like this:

$('div.img img').attr('src');

If you needed to do something with all of them, you could use something like this:

$('div.img img').each(function()
{
    var src = $(this).attr('src');

    // Do whatever you need to do with src...
});


var get="?";
$("#data img").each(function(index){
   get += "img"+(index+1)+"="+$(this).attr("src")+"&";
});
get = get.slice(0, -1);


I would build a JavaScript object and then send it directly to $.post()

data = {};

$("#data img").each(function(eIndex, e){
  data["img"+eIndex] = $(e).attr("src");
});

$.post("/some/path.php", data, fn);


In the spirit of using jQuery, here's one that uses jQuery $.map() to create a javascript array and $.param() to parameterize it.

$.param(
    $('div.img img')
        .map(function(i) { return  { name: 'img'+i, value: $(this).attr('src')}; })
);

Your result will be:

"img0=imageurl_1&img1=imageurl_2&img2=imageurl_3&img3=imageurl_4"

Replace the 'img'+i with your own name or id for your own needs.


$('img').each(function(idx, elem){
 elem.attr('src'); 
});
0

精彩评论

暂无评论...
验证码 换一张
取 消