通过find()和each()迭代分配唯一ID

时间:2015-10-03 21:53:10

标签: javascript jquery jquery-ui

对于每个.chart_edit_toolbar及其子input元素,我想在初始化"-" + index之前将id附加到buttonset attr。对于每个重复的idbuttonset广播,此处的目标是唯一的input

$("div.chart_edit_toolbar").each(function(index,event) {
    $(this)
        .attr("id", $(this).attr("id") + "-" + index) // works as expected
        .find("input")
            .each(function(i,e) {
                $(this).attr("id", $(this).attr("id", + "-" + index)); // "[object Object]"
            })
        .buttonset();
});

在上面的代码中,id的{​​{1}}按预期更改,但div字段的id变为input

如果你有一个,我也会采取更有效的方式来实现这个目标。我还需要更改随附的[object Object]元素的for属性,以便您可以在解决方案中包含该属性,我们将不胜感激。感谢。

示例HTML(在几个jQuery UI选项卡中重复几次):

label

如果它对其他人有帮助,这是实施的解决方案:

<div id="chart_edit_toolbar" class="alignleft chart_edit_toolbar">

                        <input type="radio" id="arrow_tool" name="tool_radio" checked="checked">
                        <label for="arrow_tool">Arrow</label>

                        <input type="radio" id="text_tool" name="tool_radio" >
                        <label for="text_tool">Text</label>

                        <input type="radio" id="tri_tool" name="tool_radio">
                        <label for="tri_tool">Tri</label>

                        <input type="radio" id="rect_tool" name="tool_radio">
                        <label for="rect_tool">Rect</label>

                        <input type="radio" id="clear_tool" name="tool_radio">
                        <label for="clear_tool">CLEAR</label>

                        <input type="radio" id="undo_tool" name="tool_radio">
                        <label for="undo_tool">UNDO</label>

                    </div>

1 个答案:

答案 0 :(得分:1)

你的括号在错误的位置。

$(this).attr("id", $(this).attr("id", + "-" + index)); 
                                    ^

应该是

$(this).attr("id", $(this).attr("id") + "-" + index);

attr setter返回jQuery对象,因此在字符串化时你得到[object Object]

相关问题