简体   繁体   English

动态生成目标元素(jQuery)

[英]Target elements generated dynamically (Jquery)

I current have something similar to this ( http://jsfiddle.net/my7bM/ ) working on the page as long as it is generated using php, however on another page there is the same functionality happening, only on that page the content is dynamically generated using Ajax and the script does not work (JS newbie therefore any help most appreciated) 我目前有类似的东西( http://jsfiddle.net/my7bM/ )在页面上工作,只要它是使用php生成的,但是在另一页面上发生了相同的功能,仅在该页面上的内容是使用Ajax动态生成的脚本不起作用(因此,JS新手非常感谢帮助)

I've tried this but it still does not work 我已经尝试过了,但是还是不行

$('.read-more').on("click", function (e) {
    e.preventDefault();
    $(this).closest('.member-content').next('.contentDiv').find('.myContent').show();
    $(this).hide();
    return false;
    );

$('.close-more').on("click", function (e) {
    e.preventDefault();
    $(this).closest('.contentDiv').prev('.member-content').find('.read-more').show();
    $(this).closest('.myContent').hide();
    return false;
});

Any help would be great, Thanks! 任何帮助都会很棒,谢谢!

You need event delegation for handling events to dynamically added DOM . 您需要事件委托来处理事件以动态添加DOM。

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future. 事件委托使我们可以将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有子对象触发,无论这些子对象现在存在还是将来添加。

try this: 尝试这个:

 $(document).on("click",'.close-more', function (e) {
  e.preventDefault();
  $(this).closest('.contentDiv').prev('.member-content').find('.read-more').show();
  $(this).closest('.myContent').hide();
  return false;
});

Also prefer using the closest parent DOM(which remains static) instead of $(document) 还希望使用最接近的父DOM(保持静态)而不是$(document)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM