Changing name attribute using jQuery

前端 未结 3 2011
梦谈多话
梦谈多话 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:20

    Karim is right,

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

    could be changed to

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

    to change the name first, $("#" + id) is the same as getElementById and once you change the id, its no longer the element you meant to refer to

    0 讨论(0)
  • 2020-12-05 23:33

    Instead of chaining you can pass into .attr()

    {
        "id" : "sel" + rowIndex ,
        "name" : "sel" + rowIndex
    }
    

    A lot of jQuery functions accept objects like above when you have to pass in (string comma string) data like .css() and .animate()

    0 讨论(0)
  • 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);
    ...
    
    0 讨论(0)
提交回复
热议问题