$(this).attr(“id”) not working

前端 未结 9 645
情书的邮戳
情书的邮戳 2020-12-30 02:55

as the title says, I keep getting \"undefined\" when I try to get the id attribute of an element, basically what I want to do is replace an element with an input box when th

相关标签:
9条回答
  • 2020-12-30 03:28

    What are you expecting $(this) to refer to?

    Do you mean sel.attr("id"); perhaps?

    0 讨论(0)
  • 2020-12-30 03:30

    You can do

    onchange='showHideOther.call(this);'

    instead of

    onchange='showHideOther(this);'

    But then you also need to replace obj with this in the function.

    0 讨论(0)
  • 2020-12-30 03:34

    In the function context "this" its not referring to the select element, but to the page itself

    • Change var ID = $(this).attr("id"); to var ID = $(obj).attr("id");

    If obj is already a jQuery Object, just remove the $() around it.

    0 讨论(0)
  • 2020-12-30 03:40

    Change

    var ID = $(this).attr("id");
    

    to

    var ID = $(obj).attr("id");
    

    Also you can change it to use jQuery event handler:

    $('#race').change(function() {
        var select = $(this);
        var id = select.attr('id');
        if(select.val() == 'other') {
            select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
        } else {
            select.hide();
        }
    });
    
    0 讨论(0)
  • 2020-12-30 03:43

    Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.

    Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.

    function showHideOther(obj){ 
        var sel = obj.options[obj.selectedIndex].value;
        var ID = obj.id;
    
        if (sel == 'other') { 
            $(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
        } else {
            $(obj).css({'display' : 'none'});
        }
    }
    
    0 讨论(0)
  • 2020-12-30 03:47

    Remove the inline event handler and do it completly unobtrusive, like

    ​$('​​​​#race').bind('change', function(){
      var $this = $(this),
          id    = $this[0].id;
    
      if(/^other$/.test($(this).val())){
          $this.replaceWith($('<input/>', {
              type: 'text',
              name:  id,
              id: id
          }));
      }
    });​​​
    
    0 讨论(0)
提交回复
热议问题