代码之家  ›  专栏  ›  技术社区  ›  KellysOnTop23

在jQuery“click”中创建的对象即使创建了新的对象也会保持

  •  1
  • KellysOnTop23  · 技术社区  · 8 年前

    非常新的JQuery,所以我的代码可能不是最好的方法,所以这里的提示会很好。。。

    reqObj 在单击函数中创建的函数似乎永远不会被忽略。如果函数通过和I控制台运行。记录我创建的新对象和之前创建的所有对象。我试着将对象放在函数之外,但不起作用。我相信这是一个快速解决方案。谢谢你的帮助。

    P、 div是基于传入数据在javascript中动态创建的

    $(document).on('click', '.profileDiv', function(){
        var outer = this;
        $("#myModal").modal('toggle');
        $('#headerModal').text('Would like to request a session with ' + $(outer).find('#pro_first_name').text());
        $(document).on('click', '#modalRequest', function(){
          var reqObj = {};
          reqObj = {
            pro_id : $(outer).attr('id'),
          }
          console.log(reqObj);
        });
    });
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   synthet1c    8 年前

    您不应该在另一个事件回调中真正绑定和事件,因为您使用的是事件委托,所以实际上不需要这样做。您试图做的是将数据从一个事件的回调传递到另一个。

    您可以通过使用所有函数都可以访问的全局变量来实现这一点,但这是一种反模式,因为它可以通过任何代码段随时更改。

    然而,jQuery提供了一种更好的方法将元数据附加到元素,以便您可以使用 jQuery.fn.data 这比诉诸全局变量要好得多。

    $.fn.modal = function(){}
    
    $(document).on('click', '.profileDiv', function() {
      var outer = this;
      $("#myModal")
        .data('reqObj', {
          pro_id : $(outer).attr('id'),
        })
        .modal('toggle');
      
      $('#headerModal').text(
        'Would like to request a session with ' +            
        $(outer).find('#pro_first_name').text()
      );
    });
    
    $(document).on('click', '#modalRequest', function(){
      console.log($("#myModal").data());
    });
    
    $(document).on('keyup', '#messageReq', function(e){
      var $modal = $('#myModal')
      // get the data
      var data = $modal.data()
      // assign the text field value to the data
      data.msg = this.value
      // reset the data on the modal element
      $modal.data(data)
    })
    .profileDiv,
    #modalRequest {
      width: 200px;
      height: 200px;
      background: #bada55;
      float: left;
      margin: .5em;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="profileDiv" id="myModal">profileDiv</div>
    <div id="modalRequest">
      modalRequest
      <input id="messageReq" 
        type="text" 
        name="messageRequest" 
        placeholder="Present yourself" />
    </div>