【问题标题】:Append array value to ID attribute of selected elements将数组值附加到所选元素的 ID 属性
【发布时间】:2016-06-12 13:12:16
【问题描述】:

简单地说,我正在尝试使用 jQuery 将一个数值(当前存储在一个数组中)附加到多个指定元素的“id”属性的末尾。

$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink').attr("id", // Append modCount[0].toString() to each existing ID);

我正在努力解决如何附加数值,而不是简单地将 ID 设置为等于数值。我不想丢失现有的 ID。

在示例中,首选的结果 ID 应该是:

#headerAfirstLink1, #headerAsecondLink1, #headerAthirdLink1, #headerAfourthLink1

(如果 modCount[0] == 1)。

我确信它非常简单,但希望得到一些指导。 谢谢

【问题讨论】:

  • 你也可以添加HTML吗?

标签: javascript jquery jquery-selectors attributes


【解决方案1】:

尝试使用.attr("attrName" , callBack)签名来实现你想要的。

$('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
  .attr("id", function(_,id){
     return id +  modCount[0];
  });

不要将第一个参数与 callBack 混淆。是索引。我只是在那里使用了下划线,因为在我们的案例中不需要它。只是为了隐藏它的视觉效果。

或者最好/可维护的方法是为这四个元素设置一个通用类(例如:测试),并在那里使用class selector 而不是multiple selector

$('.test').attr('id', function(_, id) {
    return id + modCount[0];
});

【讨论】:

    【解决方案2】:

    您可以使用.attr(attributeName, function) 语法来更新每个相应元素的属性值。

    $('#headerAfirstLink, #headerAsecondLink, #headerAthirdLink, #headerAfourthLink')
        .attr("id", function(index, oldId) {
            // oldId is the attribute value
            return oldId + modCount[0];
        });
    

    以防万一,要更新ID以header开头的所有元素的属性,可以使用attribute starts with selector

    $('[id^="header"]').attr('id', function(index, oldId) {
        return oldId + modCount[0];
    });
    

    【讨论】:

    • 很棒,按预期工作。但是,我不太明白 oldId 是如何填充当前 ID 的。 jQuery 是否会自动将现有属性名称传递给回调函数?
    • @JordanDolan 该代码与each 相同。遍历每个匹配的元素并将 ID 作为第二个参数传递给 attr 回调函数。
    猜你喜欢
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2014-02-24
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    相关资源
    最近更新 更多