使用jQuery更改名称属性 [英] Changing name attribute using jQuery

查看:52
本文介绍了使用jQuery更改名称属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery函数,尝试更改元素的idnameclass属性值.

I've got a jQuery function that attempts to change the id, name and class attribute values of an element.

idclass更改似乎有效,但是出于某些奇怪的原因,尝试更改元素的name永远无效.

The id and class change seems to work but for some curious reason, trying to change the name of the element never works.

这是我的代码:

$(document).ready(function () {

$("table select").live("change", function () {

    var id = $(this).attr('id');

    if ($(this).attr('classname') != "selected") {
        var rowIndex = $(this).closest('tr').prevAll().length;
        $.getJSON("/Category/GetSubCategories/" + $(this).val(), function (data) {
            if (data.length > 0) {

                $("#" + id).attr('classname', 'selected');
                $("#" + id).attr('id', 'sel' + rowIndex);
                $("#" + id).attr('name', 'sel' + rowIndex); // this never works

                var position = ($('table').get(0));

                var tr = position.insertRow(rowIndex + 1);
                var td1 = tr.insertCell(-1);
                var td2 = tr.insertCell(-1);
                td1.appendChild(document.createTextNode('SubCategory'));
                var sel = document.createElement("select");
                sel.name = 'parent_id';

                sel.id = 'parent_id';

                sel.setAttribute('class', 'unselected');
                td2.appendChild(sel);

                $.each(data, function (GetSubCatergories, Category) {
                    $('#parent_id').append($("<option></option>").
       attr("value", Category.category_id).
       text(Category.name));
                });
            }

        });

    }
});
}); 

推荐答案

name不能更改,因为一旦修改了id,后续表达式中的选择器(使用未修改 id)什么都没选择:)

The name cannot be changed because once you have modified the id, the selector in the subsequent expression (which uses the unmodified id) is selecting nothing :)

$("#" + id).attr('id', 'sel' + rowIndex);
$("#" + id).attr('name', 'sel' + rowIndex); // this can't ever work

尝试像这样将它们链接在一起,以保持对当前选择的引用:

Try chaining them together like this, to keep the reference to the current selection:

$("#" + id).attr('id', 'sel' + rowIndex)
           .attr('name', 'sel' + rowIndex);

或者,对语句重新排序,以便您在更改ID之前先更改名称(和/或其他名称).

Alternatively, reorder the statements such that you change the name (and/or whatever else) before changing the id:

$("#" + id).attr('name', 'sel' + rowIndex);
$("#" + id).attr('id', 'sel' + rowIndex);

您还可以将所选内容分配给变量:

You can also assign the selection to a variable:

var $el = $("#" + id);
$el.attr("id", 'sel' + rowIndex);
...

这篇关于使用jQuery更改名称属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆