jquery dynamic id

后端 未结 4 1174
广开言路
广开言路 2021-01-06 08:56

i use such code to access item

function f(id){

$(\"#\"+id).val(); // with analogy $(\"#id item\")
}

is it correct? is any other methods?<

相关标签:
4条回答
  • 2021-01-06 09:35

    You could use PureDom

    function f(id){
       return document.getElementById(id).value;
    }
    

    Take that, jQuery!

    0 讨论(0)
  • 2021-01-06 09:38

    If you want to return the value of an element with specified id, then yes as that is what seems to be logical purpose of your function:

    function f(id){
      return $("#" + id).val();
    }
    

    The functions should assume that an element with specified id exists and then it returns you the value of that element. This should work for input fields as well as textarea. If however, it is any other element, you might want to use html() or text() instead of val() eg:

    function f(id){
      return $("#" + id).html();
      // return $("#" + id).text();
    }
    
    0 讨论(0)
  • 2021-01-06 09:38

    From the jQuery API website:

    .val() Returns: String, Array

    Description: Get the current value of the first element in the set of matched elements.

    What It's not clear to me when you say

    // with analogy $("#id item")

    is if you want to have ONLY one child item of the one that is identifiedby #id or if you need the item that is identified by item#id.

    Your code is perfect if you are passing a string like "hello" inside your code and you want to get the DOM element with ID of #hello.

    0 讨论(0)
  • 2021-01-06 09:44

    Yes this is perfectly valid way to access the element having its id.

    0 讨论(0)
提交回复
热议问题