开发者

Using JavaScript (jQuery), how can I cycle through all 'a' tags on a page, one at a time, and assign an individual style to each?

开发者 https://www.devze.com 2023-01-18 00:18 出处:网络
Let me try to explain... Lets say I have the following \'a\' tags on a page: <a href=\"img1.jpg\" class=\"myClass\" alt=\"0,0,600,200\"></a>

Let me try to explain... Lets say I have the following 'a' tags on a page:

<a href="img1.jpg" class="myClass" alt="0,0,600,200"></a>
<a href="img2.jpg" class="myClass" alt="200,0,600,75"></a>
<a href="img3.jpg" class="myClass" alt="275,0,600,200"></a>
<a href="img4.jpg" class="myClass" alt="475,0,600,50"></a>
<a href="img5.jpg" class="myClass" alt="525,0,600,100"></a>
<a href="img6.jpg" class="myClass" alt="625,0,600,200"></a>

and I want to cycle through all 'a' tags with class 'myClass' and read the alt tag and based on its value assign specific 'style' attributes.

I tried the following:

// get value of alt attribute
var tmp = $("a.myClass").attr('alt');
// split value into an array
var partsArray = tmp.split(',');
// assign array values to a dedicated variable
var a = partsArray[0];
var b = partsArray[1];
var c = partsArray[2];
var d = partsArray[3];

// create inline style string
var style;
style = style + "position:absolute;display:block;";
style = style + "border:1px solid red;";
style = style + "width:" + c + "px;";
style = style + "height:" + d + "px;";
style = style + "top:" + a + "px;";
style = 开发者_如何学Cstyle + "left:" + b + "px;";

// add the style attribute and its value
$('a.myClass').attr('style', style);

but it takes the value of the first 'a' tag 'alt' attribute and assigns the style to all 'a' tags. What I am trying to do is read each 'a' tag, get the 'alt' value and assign a style to THAT 'a' tag only THEN read the next 'a' tag ...

Is there a way to accomplish this WITHOUT having to assign a unique ID or class to each 'a' tag?

I am totally new to jQuery and have spent hours trying and googleing this issue and can't figure out how.

Someone PLEASE help.


You can use the each method like this:

$('a.myClass').each(function(){
  var tmp = $(this).attr('alt');

  // your further code...
});

The each will iterate over all links with class myClass and get each link's alt value stored in tmp variable you can act upon.


You're actually not too far from where you need to be.

// get value of alt attribute
$("a.myClass").each(function() {
  var tmp = $(this);

  // split value into an array
  var partsArray = tmp.attr("alt").split(',');

  // assign array values to a dedicated variable
  var t = partsArray[0];
  var l = partsArray[1];
  var w = partsArray[2];
  var h = partsArray[3];

  tmp.css({
    "position" : "absolute",
    "display" : "block",
    "border" : "1px solid red",
    "width" : w,
    "height" : h,
    "top" : t,
    "left" : l
  });
});
0

精彩评论

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