我从Array标记中的数据库中获取带有jinja2的条目的<a>,item表示id,而item1是属性(例如名称)。
我想在我的ajax调用中引用id,所以如果我单击anchortag中的任何内容,它就会引用id,现在一旦我单击了anchortag中的任何内容,所有事情都会运行而不引用id。
{% for item in people %}
   <a id="foo" class="foo">{{item[1]}}</a>
{% endfor %}JAVASCRIPT/AJAX
{% for item in people %}
$(".foo").click(function(evt) {
$.ajax({
 url: "/~s6/cgi-bin/people.py",
 async: true,
 type: "post",
 datatype:"json",
 data: {'peopleid': {{item[0]}}},
      success: function(result) {
        console.log(result)
        //console.log(result.peopleinfo.surname)
       // console.log(result.peopleinfo.othernames)
        console.log(result.familyinfos)
         html = "<table class='table table-striped table-bordered table-condensed'>" + "<tr><th>Old Name</th><td>" + result.peopleinfo.surname  + "</td></tr>"' + "<table>"
$('#infoTab').html(html)
 $("#placenameModal").modal("show");
      }
  });
  });
 {% endfor %} 发布于 2018-07-03 13:40:43
也许是这样的:
{% for item in people %}
   <a id="{{item[0]}}" class="foo">{{item[1]}}</a>
{% endfor %}Javascript
$(document).on('click', '.foo', handleClick)
function handleClick(e) {
  $.ajax({
    url: "/~s6/cgi-bin/people.py",
    type: 'POST',
    data: {
      peopleid: $(this).attr('id')
    },
    success: handleModal
  })
}
function handleModal(response) {
  // Do stuff here with your response
}发布于 2018-07-03 13:48:50
您可以在data属性中添加所需的信息。
{% for item in people %}
    <a id="foo" class="foo" data-people-id="{{item[1]}}" data-people-name="{{item[1]}}">{{item[1]}}</a>
{% endfor %}然后,只需获得所需的数据,当一个锚被点击。
function anchorClickHandler(evt) {
    var anchor = $(this)[0];                    // get the anchor DOM element, unwrapped from jQuery
    var peopleId = anchor.dataset.peopleId;     // get the peopleId from the data attribute
    var peopleName = anchor.dataset.peopleName; // you can do the same with the name, if you want
    $.ajax({
        url: "/~s6/cgi-bin/people.py",
        async: true,
        type: "post",
        datatype: "json",
        data: {
            'peopleid': peopleId,   // pass in the peopleId from the specific anchor that was clicked.
        },
        success: function(result) {
            console.log(result)
            // console.log(result.peopleinfo.surname)
            // console.log(result.peopleinfo.othernames)
            console.log(result.familyinfos)
            html = '<table class="table table-striped table-bordered table-condensed">' +
                        '<tr>' +
                            '<th>Old Name</th>' +
                            '<td>' + result.peopleinfo.surname + '</td>' +
                        '</tr>' +
                    '</table>'
            $('#infoTab').html(html)
            $("#placenameModal").modal("show");
        }
    });
}
$(".foo").on('click', anchorClickHandler);在实际分配之外定义处理程序也是一个不错的主意。
如果要在循环中定义处理程序,则将绑定处理程序的副本,而不是绑定处理程序本身。
虽然您不会注意到在较小的页面上有什么不同,但它的扩展性很差,并且会影响更大页面上的性能。
https://stackoverflow.com/questions/51155785
复制相似问题