在jQuery中创建的对象' click'即使创建了新的,也会持续存在

时间:2016-10-15 16:55:44

标签: javascript jquery html scope this

对JQuery来说很新,所以我的代码可能不是最好的方法,所以提示会很好......

但问题是点击功能内部创建的reqObj似乎没有被解雇。如果函数运行并且我在console.log中,那么对象我将获得创建的新对象以及之前创建的所有对象。我尝试将对象放在函数之外,但这不起作用。我确定这是一个快速修复。谢谢你的帮助。

P.S。 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 个答案:

答案 0 :(得分:3)

You shouldn't really bind and event inside another event callback, and as you are using event delegation you don't really need to. What you are trying to do is pass data from the callback of one event to another.

You can achieve this through using global variables that all functions have access to, however this is an anti pattern as it can change at anytime by any piece of the code.

jQuery gives you a better way however to attach metadata to elements so you can easily transfer or store the state using jQuery.fn.data it's much better than resorting to global variables.

$.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>