javascript - Ajax 链接作为列表项

标签 javascript html ajax

我想要做什么 我正在构建一个简单的 UI,您可以在其中使用纯 Javascript 在数组中动态搜索。结果列表是使用 AJAX 从 Django 后端获取数据并在模式中显示详细信息的链接。

我得到了什么 搜索结果列表工作正常。但如果我点击链接,AJAX 功能不会被触发。

如果我直接在 HTML 中尝试相同的链接(不是由 Javascript 生成),它工作正常并且该函数被调用。

注意 不要关注 Django 部分。我只是想知道为什么当我在Javascript列表中生成链接时没有调用AJAX函数。

欢迎任何线索。提前致谢!

let arr = ["anagrams-of-string-(with-duplicates)", "array-concatenation", "array-difference", "array-includes",]

function updateResult(query) {
    let resultList = document.querySelector(".result");
    resultList.innerHTML = "";

    arr.map(function(algo){
        query.split(" ").map(function (word){
            if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
   resultList.innerHTML += `<li class="list-group-item">
                <a href="" id="${algo}" data-id="${algo}" class="artist-title show_product" style="color: black; padding-left: 0;" data-toggle="modal">${algo}test</a>
                </li>`;
                console.log("This works fine");
            }
        })
    })
}

$(function(){
            $('.show_product').on('click', function (e) {
                e.preventDefault();
                let product_id = $(this).attr('id');
                console.log("This function is called");

                $.ajax({
                    url:'/backend/form-fill/',
                    type:'POST',
                    data: $('#form_have_product_'+product_id).serialize(),
                    success:function(response){
                        console.log(response);
                        $('.show_product').trigger("reset");
                        openModal(response);
                    },
                    error:function(){
                        console.log('something went wrong here');
                    },
                });
            });
        });

        function getFormData(content_data){
          $('#categoria_producto').text(content_data.field1);
          $('#estatus_contenido').text(content_data.field2);
          $('#descripcion_brief').text(content_data.field3);
          $('#descripcion_long').text(content_data.field4);
        };
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="input-group" style="position: fixed; top: 0; z-index: 10;">
  <input oninput="updateResult(this.value)" style="font-size: 3rem; height: 15vh;" type="search" class="form-control" placeholder="Search..." />
</div>

<div>
    <ul class="list-group result" style="margin-top: 15vh;"></ul>
</div>

最佳答案

$('.show_product').on('click', function (e) {

上面选择了 DOM 中尚不存在的元素,因为它们是根据您的搜索动态创建的。为了能够向动态创建的元素添加事件监听器,您必须将其更改为:

$(document).on('click', '.show_product', function(e) {

这意味着“事件附加到文档中,当我们在文档中单击时,我们会检查目标以查看它是否是我们想要的元素。” (基本上)的一种简写方式:

$(document).on('click', function(e) {
  if (e.target == document.querySelector('.show_product')) {
    // do the thing
  }
});

关于javascript - Ajax 链接作为列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59182457/

相关文章:

javascript - 使用 Selenium(Javascript) 打开第二个边缘窗口时出现 WebDriverError : Unknown error,

javascript : Cannot access member function

javascript - JS : How to dynamically insert text into a SPAN?

javascript - 如何捕获倒数计时器并将其传递给 php 页面?

javascript - 如何在没有 jQuery 的情况下使用 $http 发布 urlencoded 表单数据?

javascript - 当不知道父变量时拒绝 promise

javascript - 在 JQuery 中过滤

javascript - "Autoplay"移动浏览器上的 HTML5 音频播放器

php - 这是一种有效的更新方法吗

javascript - 如何使用ajax将新页面加载到div