找不到与php添加在一起的元素或元素ID [英] can not find element or element id that is added with php

查看:79
本文介绍了找不到与php添加在一起的元素或元素ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jquery,我将新元素添加到div元素中,我还设置了新添加元素的ID,但是javascript仍找不到该新添加元素.

using jquery i am adding new elements to a div element i also have set id of new added element but still javascript can not find that newly added elements.

$.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或我该怎么办?

new elements added successfully but on button click javascript can not find that new element id. is there any way to reload only javascript or what should i do ?

     $("#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);
 }

然后出现参考错误.对此.

then comes reference error. on this.

推荐答案

jQuery在运行时仅知道页面中的元素,因此jQuery无法识别添加到DOM中的新元素.要解决此问题,请使用事件委托,将事件从新添加的项目冒泡到指向jQuery在页面加载时运行的DOM中的位置.许多人将document用作捕获冒泡事件的地方,但是不必一直走到DOM树上.理想情况下,您应该委派给页面加载时存在的最近的父级.

jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM are unrecognized by jQuery. To combat the problem use event delegation, bubbling events from newly added items up to a point in the DOM which was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally you should delegate to the nearest parent existing at the time of page load.

此外, ID必须是唯一的,特别是因为它会导致

In addition, ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements.

将选择器(从jQuery切换到Vanilla JS确实没有必要,因为您已经在使用jQuery)更改为类,并使用on()执行事件委托:

Change your selectors (switching from jQuery to vanilla JS is really not necessary since you're already using jQuery) to classes and use on() to perform the event delegation:

$(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);
})

部分问题是您需要与validator相关的特定select_division.为了使您可以执行一些DOM遍历.没有看到您的标记,我无法告诉您如何进行遍历.

Part of the problem here is you will want a specific select_division related to your validator. In order to get that you may to perform some DOM traversal. Without seeing your markup I cannot tell you how to do the traversal.

这篇关于找不到与php添加在一起的元素或元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆