jQuery .on点击仅在动态元素首次使用 [英] jQuery .on click works only the first time for dynamic elements

查看:69
本文介绍了jQuery .on点击仅在动态元素首次使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ajax动态插入网页的小部件,并将它自己的jquery放在标题中,一切正常。



粘贴一些额外的脚本来添加一些等待用户输入的动态添加的元素,它们确实工作正常,但是最初加载了widget的元素最初只能用 .click()事件,而动态元素确实有效,但第一次只有一些非常奇怪的行为,比如多次触发点击(通过点击该调用显而易见),然后完全不再工作,这可能是什么原因,是其他网站的常驻脚本与我的脚本搞乱或者是别的什么?



我正在使用所有元素:

  $('body').on('click','.page_link',someFunction); 

上面没有工作,所以我试着按照预期的方式工作,小部件,但动态添加的并不多:

  $('.page_link').click(someFunction); 
$('body').on('click','.page_link',someFunction);

感谢任何帮助。

解决方案

对于jquery中的动态加载元素,您需要重新应用事件(点击)

从jQuery 1.7开始,您可以使用jQuery。 fn.on:

  $(parentSelector).on(eventName,dynamicChild,function(){}); 


$ b $ p $(parentSelector)必须是非透明元素
您可以使用
> code> body
或者你添加动态元素的父元素



在jquery 1.7之前,你可以使用is来使用live() :

  $(selector).live(eventName,function(){}); 


I have a widget that inserts dynamically into the web page using ajax and putting its own jquery in the header, everything works fine.

but when in that widget I paste some extra scripts to add some dynamically added elements waiting on user input, they do work fine, but the elements loaded with widget initially only get binded properly with the .click() event whereas the dynamic elements do work but only for the first time with some very weird behavior, like triggering the click many times (evident by a call I make on that click) and then not working again altogether, what could be the reason here, is the resident script of other websites messing with my script or is it something else ?

I'm using for all the elements:

$( 'body' ).on('click', '.page_link', someFunction);

Above didn't work so i tried this which work as expected with the elements pre-loaded in the widget but not so much with dynamically added ones:

$( '.page_link' ).click(someFunction);
$( 'body' ).on('click', '.page_link', someFunction);

Any help is appreciated, thanks.

解决方案

For dynamically loaded elements in jquery,You need to reapply the events(click)

As of jQuery 1.7 you can jQuery.fn.on:

$(parentSelector).on(eventName, dynamicChild, function() {});

$(parentSelector) must be a non dyanamic element For which you can either use body or a parent element where you appending dynamic element

Prior to jquery 1.7 you can use was to use live():

$(selector).live( eventName, function(){} );

这篇关于jQuery .on点击仅在动态元素首次使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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