使用Ajax,jQuery获取元素后找不到元素 [英] Can't find an element after I got it using Ajax, jQuery

查看:195
本文介绍了使用Ajax,jQuery获取元素后找不到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之夜!谢谢你的阅读。





我希望能让这个问题变得简单,你可能听起来很熟悉,也许只有一个我缺少的东西。



1.我有一个用户可以选择位置的网页。

当用户登录时,他们会得到他们的保存的位置显示在第一个帖子上。





2.这些位置包含在DIV中。 DIV是高度互动的,使用onclick和类似的东西使用jQuery。





3.当用户保存另一个位置时,这样做使用AJAX:服务器获取 sa调用并使用要附加的DIV代码进行回复。然后代码附加jQuery供用户查看。



4.现在,这些新div失去了原始DIV所具有的所有功能。从开始工作的DIV加载工作正常,新的没有任何功能。





...我认为这是因为所有我的jQuery是在document.ready上触发的,然后新的DIV没有分配任何功能。



你建议我做什么?

'Night! Thank you for reading.


I'm hoping to keep this question simple, it may sound familiar to you and maybe there's just one thing I'm missing.

1. I have a webpage where users can select locations.
When users log in, they get their saved locations displayed on the very first post.


2. The locations are contained in DIVs. The DIVs are highly interactive, with onclick and things like that using jQuery.


3. When users save another location, this is done with AJAX: the server gets a call and replies with the DIV code to append. The code then gets appended with jQuery for the user to see.

4. Now, these NEW divs lose all functions the original DIVs had. The DIVs loaded since the beginning work fine, the new ones have no functionality at all.


...I think it's because all my jQuery is triggered on document.ready, and then the new DIVs don't get any function assigned.

What do you suggest I do?

推荐答案

如果您理解正确,则尝试将现有事件处理程序附加到将来的元素。根据jQuery文档:

If you understand you correctly, you are trying to attach existing event handlers to future elements. According to the jQuery document:
Quote:

事件处理程序仅绑定到当前选定的元素;它们必须在您的代码调用.on()时存在。要确保元素存在且可以选择,请将脚本放在HTML标记中的元素之后,或者在文档就绪处理程序中执行事件绑定。或者,使用委托事件来附加事件处理程序。

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated events to attach event handlers.



让我们做一些实验:

1.非委托事件,不会将slideToggle事件添加到新段落:


Let's do some experiments:
1. Non-delegate events, the slideToggle event will not be added to new paragraphs:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>


(document).ready(function(){
// non delegate
(document).ready(function(){ // non delegate


(div p)。on(click,function(){
("div p").on("click", function(){


这篇关于使用Ajax,jQuery获取元素后找不到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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