您不应该在另一个事件回调中真正绑定和事件,因为您使用的是事件委托,所以实际上不需要这样做。您试图做的是将数据从一个事件的回调传递到另一个。
您可以通过使用所有函数都可以访问的全局变量来实现这一点,但这是一种反模式,因为它可以通过任何代码段随时更改。
然而,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>