How can I use jQuery to obtain all the ids of the anchors within a specific div and convert them to a array for passing over a load/get method?
The HTML will be in the following format:
<div id="a div id">
<div style="some styling">
<span><a href="" id="the_id_1"/></span>
<span><a href="" id="the_id_2"/></span>
<span><a href="" id="the_id_3"/></span>
</div>
</div>
So in theory I'm after passing the ids of the anchors over a load method so I can refresh the content of a div based on the selected ids.
Edit #1
The id is slightly different from what I mention above.
Here is the function I'm using to obtain the id number from the anchors:
function getSelectedTierPanels(tierId) {
var conta开发者_如何学Goiner = $('#tier'+tierId+' a').map(function() {
return this.id.match(/\d+$/);
}).get();
alert(container);
return container;
}
Similar to TJ's answer, but uses the map() function to create a new jQuery object containing all the IDs, followed by get() to get a normal array from the object:
var anchors = $('#a_div_id a').map(function () { return this.id; }).get();
To get just the number from the id in the format
the_id_1
, the_id_2
, you can use one of my favourite techniques - splitting and popping:
var anchors = $('#a_div_id a').map(function () {
return this.id.split("_").pop();
}).get();
This technique splits the string into an array at each _
. The pop() method removes and returns the last item of the array, which is just the number in this case. If you wanted a different part of the array, you could refer to the item's index directly.
If your
id
is slightly different, then a regular expression might be better than splitting. What you have currently is return this.id.match(/\d+$/);
, which is just fine except that match() returns an array so you need to access the first element of that array to retrieve the full match:
return this.id.match(/\d+$/)[0];
Note that this would throw an error if there was no successful match, so you're better off storing match to a variable:
var match = this.id.match(/\d+$/);
return match ? match[0] : null;
function get_all_idz() {
var array_idz = new Array();
var total = $(".row_id").length;
for(a=0; a<=total-1; a++)
{
var abc = $(".row_id").eq(a).attr('id');
array_idz[a] = abc;
}
alert(array_idz);
}
/*IT WILL STORE IN ARRAY LIKE (10,11,12,13,14,15)*/
Something like this should work:
var anchors = [];
$('#a_div_id a').each(function() {
// `this` is the actual `a` element
if (a.id) {
anchors.push(a.id);
}
});
The selector "#a_div_id a" (note I've changed the ID a bit to make it work; no spaces allowed in IDs for use in selectors) looks for all a
elements that are descendants of the element with the ID "a_div_id". jQuery's each
loops through them, with each call to the iterator function setting this
to the actual a
element (not a jQuery object for it). From the a
element instance, you can query the id
property, which is a reflection of the id
attribute.
精彩评论