weixin_33726943 2019-12-04 18:19 采纳率: 0%
浏览 41

Ajax链接作为列表项

What I want to do I'm building a simple UI where you can search dynamically in an array with plain Javascript. The results list are links to fetch data from a Django backend with AJAX and show the details in a modal.

What I get The results list from the search works fine. But if I click on the links, the AJAX function isn't triggered.

If I try the same link directly in the HTML (not generated by Javascript) it works fine and the function is called.

Note Don't pay attention to the Django part of the thing. I just want to know why the AJAX function is not called when I generate the link in the Javascript list.

Any clues welcome. Thanks in advance!

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>

</div>
  • 写回答

2条回答 默认 最新

  • weixin_33739541 2019-12-04 18:33
    关注
    $('.show_product').on('click', function (e) {
    

    The above is selecting elements that don't yet exist in the DOM because they are created dynamically from your search. To be able to add an event listener to elements that are created dynamically, you have to change it to this:

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

    What this says is, "The event is attached to the document, and when we click in the document, we check the target to see if it is the element we desire." A short-hand way of (basically) saying:

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

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用