【问题标题】:Extra click after dynamically added HTML elements via jQuery通过 jQuery 动态添加 HTML 元素后的额外点击
【发布时间】:2019-11-13 06:45:27
【问题描述】:

我在data.html中动态添加了一些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>

在此之后,我假设使用这样的点击事件。

$('#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');
      });
    }
  });

但是当我第一次点击时,什么也没有发生。在第二次单击时,它可以正常工作。 我曾尝试在div 上使用focus(),但如果没有帮助。

这种方法也无济于事jquery functions inside of dynamically generated html not working

我在这里错过了什么?

【问题讨论】:

  • 您在此处缺少报价$.getJSON('@Url.Action("Search", "Devices", { s: $('#searchStr').val() },
  • @Roy 抱歉,Roy 这不是问题所在。它仅存在于示例代码中。已更正。
  • .deviceName上的点击事件只有在getJSON响应解析成功后才会注册,所以在调用之前点击该元素是正常的。
  • 为什么要在异步函数内部附加点击事件到文档?
  • @randomSoul 我只是想弄清楚为什么我需要点击两次。最初我把它放在异步函数之外,但我也不会工作。

标签: javascript jquery jquery-click-event


【解决方案1】:

把你的代码移到外面

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

【讨论】:

  • 我做到了。它没有帮助(((而且即使我在动态添加的HTML中使用&lt;a&gt;,我也必须单击两次才能生效。
【解决方案2】:

谢谢大家!

我在这里找到了我的解决方案 Is it possible to focus on a <div> using JavaScript focus() function?

所以我只在data.html 中使用常规&lt;a&gt;,然后在div 上使用focus 并动态添加数据。一键即可!

$('#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';
        }
    }
  });

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2011-07-05
    相关资源
    最近更新 更多