如何使用jQuery获取特定div中所有锚的ID,并将其转换为数组以通过load / get方法传递?

HTML将采用以下格式:

<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>


因此,从理论上讲,我是在将锚的id传递给load方法之后的,因此我可以根据所选的id刷新div的内容。

编辑#1

该ID与我上面提到的略有不同。

这是我用来从锚点获取ID号的函数:

function getSelectedTierPanels(tierId) {
    var container = $('#tier'+tierId+' a').map(function() {
        return this.id.match(/\d+$/);
    }).get();
    alert(container);
    return container;
}

最佳答案

TJ's answer相似,但是使用map()函数创建一个包含所有ID的新jQuery对象,然后使用get()从该对象中获取普通数组:

var anchors = $('#a_div_id a').map(function () { return this.id; }).get();



要仅从ID中以the_id_1the_id_2格式获取数字,可以使用我最喜欢的技术之一-拆分和弹出:

var anchors = $('#a_div_id a').map(function () {
    return this.id.split("_").pop();
}).get();


此技术将字符串拆分为每个_处的数组。 pop()方法删除并返回数组的最后一项,在这种情况下,这只是数字。如果需要数组的其他部分,则可以直接引用项目的索引。

如果您的id稍有不同,则正则表达式可能比拆分更好。当前使用的是return this.id.match(/\d+$/);,这很好,除了match()返回一个数组,因此您需要访问该数组的第一个元素以检索完全匹配项:

return this.id.match(/\d+$/)[0];


请注意,如果没有成功的匹配,这将引发错误,因此最好将匹配存储到变量中:

var match = this.id.match(/\d+$/);
return match ? match[0] : null;

关于jquery - 获取 anchor ID并转换为JavaScript数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3657938/

10-11 19:54
查看更多