jquery dynamic id

后端 未结 4 1197
广开言路
广开言路 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: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();
    }
    

提交回复
热议问题