jQuery passing element ID into jquery statement?

前端 未结 6 1969
野性不改
野性不改 2020-12-11 03:12

I\'d like to pass the ID of an element into a function which then calls jQuery. However, I\'m stumped as to how to actually take the ID variable and concatenate it with othe

相关标签:
6条回答
  • 2020-12-11 03:25

    I think you'd get better reuse if you passed an entire selector as a parameter, remembering that jQuery implicitly iterates over all matched elements. For a rudimentary example:

    function hideImageDescendants(selector){
        $(selector).find("img").hide();
    }
    
    0 讨论(0)
  • 2020-12-11 03:30

    When button is click then it get the button id which I later use to get it's field data, use + operator to dynamic change id

    $('.btnsave').click(function() 
      {
          btnvalue = $(this).val();
          //alert(btnvalue);
          adjust_value = $('#adjust_value'+btnvalue).val();
          ado = $('#ado'+btnvalue).val();
          amount =  $('#amount'+btnvalue).val();
          description = $('#description'+btnvalue).val();
          //alert(adjust_value+ado+amount+description);
          
      })

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

    Just do this--

    myfunction('obj')
    function myfunction(obj){
    $('#'+obj+' img').show();
    }
    

    Or, even

    myfunction($('#2 img a'));
    
    myfunction(jqobj){
    jqobj.show();
    }
    
    0 讨论(0)
  • 2020-12-11 03:35
    myFunction("#myObject");
    
    function myFunction(IDofObject){
    
        $(IDofObject+" img").doSomething...
    
    }
    

    Try that.

    0 讨论(0)
  • 2020-12-11 03:42

    Ugh. one of those '2 seconds after you ask you figure out...' questions:

    function myFunction(IDofObject){
    
        $(IDofObject+" img").doSomething...
    
    }
    
    0 讨论(0)
  • 2020-12-11 03:46

    Don't wrap the parameter in quotes:

    function myFunction(IDofObject) {
        $( IDofObject + " img" ).doSomething();
    }
    

    Also, you may want to consider adding the hash character inside the function so you can pass it the actual id, not a selector.

    myFunction( $('.classSelector :first').attr('id') );
    
    function myFunction(IDofObject) {
        $( "#" + IDofObject + " img" ).doSomething();
    }
    
    0 讨论(0)
提交回复
热议问题