JQuery 使用 JsRender 渲染 html 后点击侦听器未触发

JQuery on click listener not firing after rendering html with JsRender

我正在尝试将点击侦听器附加到通过 JsRender 呈现后页面上的 DOM 元素,但是似乎遇到了一些困难..

标记:

    <button id="placeBid" data-attr-saleId="{{:id}}" class="btn btn-lg btn-add-to-cart"><span class="glyphicon glyphicon-shopping-cart"></span>Bid on this item</button>

Jquery点击监听代码:

  $(document).ready(function(){

  $('#placeBid').on('click','#templateContainer', function () {

          console.log('Clicked place bid')

          const saleId = $(this).attr('data-attr-saleId')
          if (!saleId) return

          $.ajax({
            url: '/sale/placeBid',
            data: {
              bidAmount: $('#amount').val(),
              hotelSale: saleId,
              currency: $('#currencies:selected').val()
            },
            method: 'POST',
            success: function (res, ts, xhr) {
              if (xhr.status == 200 && res.status == 200) {
                $.toaster({priority: 'info',message: 'Succesfully bidded on sale'})
              }else {
                //handle error
              }
            }
          })
        })
 });

html 通过 jsRender

渲染到 templateContainer 模板中
 const html = template.render({viewLocalsHere});
 $('#templateContainer').html(html)

在 document.ready 函数中记录 console.log($('#placeBid')) 显示正在检测元素,并且在附加 onclick 处理程序时存在,但是单击按钮不会记录 Clicked place bid

可能是什么问题?谢谢

我认为你误用了 jquery 的 on 函数。

http://api.jquery.com/on/

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

为了调用您的函数,id 为 '#placeBid' 的元素必须有一个 id 为 '#templateContainer' 的元素作为其后代。这是委托事件。看来您正在寻找直接绑定的事件,因此从您的参数中删除 '#templateContainer',点击处理程序将绑定到按钮。

$('#placeBid').on('click', function () {
    console.log('Clicked place bid')
    ...
})