简体   繁体   English

通过 jQuery 动态添加 HTML 元素后的额外点击

[英]Extra click after dynamically added HTML elements via jQuery

I add some html dynamically in data.html我在 data.html 中动态添加了一些data.html

<div class="d-flex " id="deviceSeearchRecords">
  <div class="p-2 flex-grow-1 ">
    <button type="button" class="btn deviceName " data-href="@Url.Content(string.Format(" ~/Devices/Details/{0} ", @item.ID))">
        @item.FullName
    </button>
  </div>
</div>

After this I assume to use click event like this.在此之后,我假设使用这样的点击事件。

$('#searchResultContainer').html('');
$.getJSON('@Url.Action("Search", "Devices")', {
    s: $('#searchStr').val()
  },
  function(data) {
    if (data.success === true) {
      $('#searchResultContainer').append(data.html);
      $(document).on('click', '.deviceName', function(e) {
        e.preventDefault();
        e.stopPropagation();
        // console.log('deviceName ' + $(this).data('href'));
        window.location.href = $(this).data('href');
      });
    }
  });

But when I click first time then nothing happens.但是当我第一次点击时,什么也没有发生。 On second click it works as it should.在第二次单击时,它可以正常工作。 I have tried to use focus() on div but if does not help.我曾尝试在div上使用focus()但如果没有帮助。

This approach does not help as well jquery functions inside of dynamically generated html not working此方法也无济于事

What do I missing here?我在这里想念什么?

Move your code to the outside将代码移到外部

$(document).on('click', '.deviceName', function(e) {
  e.preventDefault();
  e.stopPropagation();
  // console.log('deviceName ' + $(this).data('href'));
  window.location.href = $(this).data('href');
});

Thanks to all!谢谢大家!

I found my solution here Is it possible to focus on a <div> using JavaScript focus() function?我在这里找到了我的解决方案是否可以使用 JavaScript focus() function 专注于 <div>?

So I just use a regular <a> within data.html and after this focus on the div with dynamically added data.因此,我只在data.html中使用常规<a> ,然后将focus放在动态添加数据的div上。 And one click works!而且一键有效!

$('#searchResultContainer').html('');
$.getJSON('@Url.Action("Search", "Devices")', {
    s: $('#searchStr').val()
  },
  function(data) {
    if (data.success === true) {
       if (data.success === true) {
             $('#searchResultContainer').html(data.html);   
             window.location.hash = '#searchResultContainer';
        }
    }
  });

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

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