Changing name attribute using jQuery

前端 未结 3 2018
梦谈多话
梦谈多话 2020-12-05 23:05

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

The id

3条回答
  •  囚心锁ツ
    2020-12-05 23:43

    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);
    

    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);
    ...
    

提交回复
热议问题