Jquery更改名称属性
我有一个JQuery函数,试图改变元素的id,名称和类。 id和class更改似乎有效,但出于一些奇怪的原因,尝试更改元素的名称永远不会起作用。
$(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($(""). attr("value", Category.category_id). text(Category.name)); }); } }); } }); });
name
无法更改,因为一旦修改了id
,后续表达式中的选择器(使用未修改的 id)就不会选择任何内容:)
$("#" + id).attr('id', 'sel' + rowIndex); $("#" + id).attr('name', 'sel' + rowIndex); // this can't ever work
尝试将它们链接在一起,以保持对当前选择的引用:
$("#" + id).attr('id', 'sel' + rowIndex) .attr('name', 'sel' + rowIndex);
或者,重新排序语句,以便在更改ID 之前更改名称(和/或其他任何内容):
$("#" + id).attr('name', 'sel' + rowIndex); $("#" + id).attr('id', 'sel' + rowIndex);
您还可以将选择分配给变量:
var $el = $("#" + id); $el.attr("id", 'sel' + rowIndex); ...
卡里姆是对的,
$("#" + id).attr('classname', 'selected'); $("#" + id).attr('id', 'sel' + rowIndex); $("#" + id).attr('name', 'sel' + rowIndex);
可以改为
$("#" + id).attr('name', 'sel' + rowIndex); $("#" + id).attr('classname', 'selected'); $("#" + id).attr('id', 'sel' + rowIndex);
要先更改名称,$(“#”+ id)与getElementById相同,一旦更改了id,它就不再是你想要引用的元素了
而不是链接你可以传入.attr()
{ "id" : "sel" + rowIndex , "name" : "sel" + rowIndex }
当你必须传入(字符串逗号字符串)数据,如.css()
和.animate()
时,许多jQuery函数接受上面的对象