【问题标题】:Changing aria-control attribute value in Cloned fields更改克隆字段中的 aria-control 属性值
【发布时间】:2015-06-19 21:14:16
【问题描述】:

我已经更改了 Milan Jaric 从这个问题 Jquery Clone Form Fields and increment ID 给出的代码,但我遇到了一个问题,我试图克隆 Bootstrap 崩溃。我无法弄清楚如何更改属性“aria-control”的值。

这是我目前拥有的the demo。 ID 和 HREF 本身可以正常工作,但是当我尝试更改“aria-control”值时,引导崩溃中的所有 id 和 href 都不会从默认值更改。有什么想法吗?

JS 脚本

var regex = /^(.*)(\d)+$/i;
var cloneIndex = $(".clonedBox").length;

function clone() {
    $(this).parents(".clonedBox").clone()
        .appendTo("div#accession_boxes")
        .attr("id", "clonedBox" + cloneIndex)
        .find("*")
        .each(function () {
            var id = this.id || "";
            var match = id.match(regex) || [];

            if (match.length == 3) {
                this.id = match[1] + (cloneIndex);
                this.href = match[1] + (cloneIndex);
                this.attr("a[aria-controls]") = match[1] + cloneIndex;
            }
        })
        .on('click', '#btnAddBox', clone)
        .on('click', '#btnDelBox', remove);
    cloneIndex++;
}
function remove() {
    $(this).parents(".clonedBox").remove();
}
$("#btnAddBox").on("click", clone);

$("#btnDelBox").on("click", remove);

是的,我知道我的删除按钮不起作用,但现在不是优先事项。

编辑:

感谢 lmgonzalves,JS 脚本现在可以工作了。以下是更新后的脚本。再次感谢大家的帮助!

JS 脚本(更新)

    var regex = /^(.*)(\d)+$/i;
var cloneIndex = $(".clonedBox").length;

function clone() {
    $(this).parents(".clonedBox").clone()
        .appendTo("div#accession_boxes")
        .attr("id", "clonedBox" + cloneIndex)
        .find("*")
        .each(function () {
            var id = this.id || "";
            var href = this.href || "";
            var aria = $(this).attr("aria-controls") || "";

            var matchID = id.match(regex) || [];
            var matchHref = href.match(regex) || [];
            var matchAria = aria.match(regex) || [];

            if (matchID.length == 3) {
                this.id = matchID[1] + (cloneIndex);
                this.href = matchHref[1] + (cloneIndex);
                this.aria = matchAria[1] + (cloneIndex);
            }
        })
        .on('click', '#btnAddBox', clone)
        .on('click', '#btnDelBox', remove);
    cloneIndex++;
}
function remove() {
    $(this).parents(".clonedBox").remove();
}
$("#btnAddBox").on("click", clone);

$("#btnDelBox").on("click", remove);

【问题讨论】:

  • this.attr("a[aria-controls]") = match[1] + cloneIndex; 什么都不做,传递 2 个参数来设置

标签: javascript jquery html twitter-bootstrap


【解决方案1】:

要使用attr() 设置属性,您需要以下语法:

$(element).attr("name", value);

所以在你的代码中使用:

$(this).attr("aria-controls", match[1] + cloneIndex);

改为:

this.attr("a[aria-controls]") = match[1] + cloneIndex;

请注意,您还需要使用 $() 和 this“包装”以将其转换为 jQuery 对象并允许使用 attr() 和其他 jQuery 函数。

DEMO HERE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-27
    • 2018-01-26
    • 2021-11-19
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多