【问题标题】:JQuery on click listener not firing after rendering html with JsRender使用 JsRender 渲染 html 后点击侦听器上的 JQuery 未触发
【发布时间】:2016-12-03 07:12:14
【问题描述】:

我试图在通过 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 events onclick listener jsrender


    【解决方案1】:

    我认为你在滥用 jquery 的 on 函数。

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

    当提供选择器时,事件处理程序被称为委托。当事件直接发生在绑定元素上时,不会调用处理程序,而只会调用与选择器匹配的后代(内部元素)。 jQuery 将事件从事件目标冒泡到附加处理程序的元素(即从最内到最外的元素),并为匹配选择器的路径上的任何元素运行处理程序。

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

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

    【讨论】:

    • 啊,是的,你可能是对的,也许我的意思是 $('#templateContainer').on('click','#placeBid',function(){}) 但是,在更改之后,无论是那个还是只是 $('#placeBid') 都不会触发处理程序。
    • 没关系,我好像缓存了旧版本。改变用法使其工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    相关资源
    最近更新 更多