Javascript 如何使用jquery通过id获取动态元素值

Javascript 如何使用jquery通过id获取动态元素值,javascript,jquery,Javascript,Jquery,我不熟悉Jquery。在使用JQuery从JSP访问动态元素时遇到了一些问题 当我尝试以下代码时,它对我来说很好: function getListElement(index) { document.getElementById('dataList['+index+'].firstName').value; } function getListElement(index) { $("#dataList["+index+"].firstName").val(); } 当我尝试

我不熟悉Jquery。在使用JQuery从JSP访问动态元素时遇到了一些问题

  • 当我尝试以下代码时,它对我来说很好:

    function getListElement(index)
    {
        document.getElementById('dataList['+index+'].firstName').value;
    }
    
    function getListElement(index)
    {
        $("#dataList["+index+"].firstName").val();
    }
    
  • 当我尝试以下代码时,它不起作用:

    function getListElement(index)
    {
        document.getElementById('dataList['+index+'].firstName').value;
    }
    
    function getListElement(index)
    {
        $("#dataList["+index+"].firstName").val();
    }
    
  • 为什么第二点不起作用我可以知道原因吗……:(

    是否有其他语法来获取该值

    提前感谢……:)


    []
    在选择器中具有特殊意义。你可以考虑简化你的代码> ID <代码> S.< /P>不要使用ID的数组。每个元素的Id都应该是唯一的。如果你需要一个数组,用name代替。HTML是什么样子的?另外,jQuery使用
    [
    ]
    作为选择器,因此它不会将id与其中的
    [
    相匹配。如何调用getListElement函数?使用class-then-index,而不是如此不寻常的id,我认为firstName在这里是一个类,所以不应该转义。@Oliboy50不是
    document.getElementById('dataList['+index+'].firstName')
    这一点也值得注意,我认为
    []
    字符在
    id
    中无效。大多数浏览器可能允许这样做,但基于html规范,它们是无效的。