jQuery:附加 html 并更新 DOM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17207281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:38:07  来源:igfitidea点击:

jQuery: Append html and update DOM

jqueryhtmllive

提问by Pascal

I have this function:

我有这个功能:

$(document).on('scroll', function(e)
{
  if (processing)
     return false;

  if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.9)
  {
     processing = true;

     var resource = $('#lazyLoad').attr('href');

     $.get(resource, '', function(data)
     {
        $('#lazyLoad').remove();

        $('#content').append(data);

        step++;
        processing = false;
     });
  }
});

I add some html code to my page every time this function is called. But other Javascript functions are not triggered when I click on a newly added html button. So I guess the DOM-element was not porper updated. But how do I proper update the DOM-element?

每次调用此函数时,我都会向我的页面添加一些 html 代码。但是当我单击新添加的 html 按钮时,不会触发其他 Javascript 功能。所以我猜 DOM 元素没有更新。但是如何正确更新 DOM 元素?

My Handler looks like this:

我的处理程序看起来像这样:

$('.article_action.un_read').on('click', function(event)
{
  event.preventDefault();

  var resource = $(this).attr('href');
  var elElemente = $(this);

  $.get(resource, '', function(data)
  {
     var obj = $.parseJSON(data);

     if(obj.status == 1)
        elElemente.html('📕');
     else
        elElemente.html('📖');
  });
});

So it also uses the onfunction.

所以它也用到了这个on函数。

回答by adeneo

Try it like this :

像这样尝试:

$('#content').on('click', '.article_action.un_read', function(event) {
    event.preventDefault();

    var resource = $(this).attr('href');
    var elElemente = $(this);

    $.getJSON(resource, '', function(obj) {
        elElemente.html(obj.status == 1 ? '📕' : '📖');
    });
});

回答by Ilu

You have to bind the button clicks with delegate-events.

您必须将按钮点击与委托事件绑定在一起。

$('#parentElement').on('click', 'button', function () {});

回答by scarecrow

you need to mention the event binder declaration

您需要提及事件绑定器声明

$(<selector>).on('click', <handler>);

again inside the function which appends the html.

再次在附加 html 的函数中。

check the sample fiddle

检查示例小提琴

edit: but first you should unbind old events inside the function which appends the html to prevent callback from multiple call.

编辑:但首先你应该在附加 html 的函数内解除旧事件的绑定,以防止多次调用的回调。

$(<selector>).off();