Javascript 找不到随php添加的元素或元素id

Javascript 找不到随php添加的元素或元素id,javascript,php,jquery,Javascript,Php,Jquery,使用jquery,我向div元素添加新元素,我还设置了新添加元素的id,但javascript仍然找不到新添加的元素 $.ajax({ //ajax call type: "POST", url: "ajax/ajax.php", data: { users: values } }).done(function( msg ) { //do something with msg which is response //this line w

使用jquery,我向div元素添加新元素,我还设置了新添加元素的id,但javascript仍然找不到新添加的元素

$.ajax({  //ajax call
    type: "POST",       
    url: "ajax/ajax.php", 
    data: { users: values }
}).done(function( msg ) {
    //do something with msg which is response
    //this line will put the response to item with id `#txtHint`.
    $("#divselect").html(msg)
    //alert(msg);
});
});
已成功添加新元素,但单击按钮时,javascript无法找到新元素id。是否有办法仅重新加载javascript,或者我应该怎么做

     $("#validator").click(function (){//validator is my submit button id

     var value = document.getElementById('select_division'); //select_division is id of my new added element
     alert(value);
 }

然后是参考误差。在这一点上。

jQuery在运行时只知道页面中的元素,因此添加到DOM中的新元素无法被jQuery识别。为了解决这个问题,我们使用了从新添加的项到DOM中某个点的冒泡事件,当jQuery在页面加载上运行时,这个点就在DOM中。许多人使用
document
作为捕获冒泡事件的地方,但并不需要一直向上遍历DOM树。理想的

此外,特别是因为当您尝试与这些元素交互时,它会在和CSS中引起问题

$.ajax({  //ajax call
    type: "POST",       
    url: "ajax/ajax.php", 
    data: { users: values }
}).done(function( msg ) {
    //do something with msg which is response
    //this line will put the response to item with id `#txtHint`.
    $("#divselect").html(msg)
    //alert(msg);
});
});
将选择器(从jQuery切换到vanilla JS实际上是不必要的,因为您已经在使用jQuery)更改为类,并使用
on()
执行事件委派:

$(document).on('click', '.validator', (function (){//validator is my submit button id
    var value = document.getElementsByClassName('select_division'); //select_division is id of my new added element
    alert(value);
})

这里的部分问题是,您需要一个与您的
验证器相关的特定
选择分区
。为了得到这个结果,您可能需要执行一些DOM遍历。没有看到您的标记,我无法告诉您如何进行遍历。

问题解决了,我写错了。 这是不可能的

$("#elementid").click(function (){//v
它只适用于

var value = document.getElementById('elementid').value;

感谢您的帮助

ID应该是唯一的。您可能正在创建具有相同ID的多个元素!另一种情况是在处理程序委托之后创建元素。如果是这样,您需要读取委托事件:parent.on('click','$(createdEl),function(){});如果答案解决了你的问题,考虑接受答案。下面是如何返回此处并对勾号/复选标记执行相同操作,直到其变为绿色。这将通知社区,找到了解决方案。否则,其他人可能会认为问题仍然悬而未决,并可能希望发布(更多)答案。您将获得积分,并鼓励其他人帮助您。欢迎来到Stack!