我有一个模态
<div class="modal fade" id="addData" tabindex="-1" role="dialog" aria-labelledby="addModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="">ADD New User</h4>
</div>
<div class="modal-body">
<form method="POST">
<div class="form-group">
<label for="name" class="control-label">Name:</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="location" class="control-label">Location:</label>
<input type="text" class="form-control" id="location" >
<div id="location-results"></div>
</div>
<div class="form-group">
<label for="website" class="control-label">Website:</label>
<input type="text" class="form-control" id="website" >
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="create" name="create" >ADD</button>
</div>
</div>
</div>
</div>
然后当我使用input
在id=location
中输入内容时,某些数据会插入位置输入下方div
id='location-results'
,我会使用Ajax来获取数据库中位置表的位置。
function findLocation(){
//Get the Value From Location Search Input.
var locationQuery = $('#location').val();
//Send Ajax Request To findlocation.php File That Connects To The Locations Database And Return 5 `<p>` Elements With Location Name Inside Each `<p>`.
$.ajax({
url:"findlocation.php",
type: 'POST',
async: true,
//Passing The Value From Location Search Input.
data: {"locationQuery": locationQuery},
success: function( data, textStatus, jQxhr ){
//Insert Returned 5 `<p>` Elements Into The Div With ID location-results Beneath The Searching Input.
$('#location-results').html( data );
}
});
}
//Run findLocation (The Function Above) on Specific Events.
$( "#location" ).on('keyup input paste cut', findLocation);
来自Ajax请求的数据如下所示:
<p class="foundLocation" >First Place</p>
<p class="foundLocation" >Second Place</p>
<p class="foundLocation" >Third Place</p>
<p class="foundLocation" >Fourth Place</p>
<p class="foundLocation" >Fifth Place</p>
然后当我点击其中一个获取的位置时,我应该获得元素内容
//Select All Elements With Class foundLocation (The 5 p elements).
var found_locations = document.querySelectorAll('.foundLocation');
found_locations.forEach(function(el){
//On Clicking On One Of The 5 `p` Elements.
el.addEventListener('click', function(){
//Insert Location Name Inside The Clicked `p` Element Into The Location Searching Input.
$('#location').val(locationName);
});
});
但是当我点击其中一个p
元素并class='foundLocation'
时,没有任何反应,我甚至尝试在console.log('some text');
范围内found_locations.forEach(function(el){
,但没有打印出任何内容控制台。
答案 0 :(得分:0)
使用AJAX更新DOM时,必须将事件绑定到插入的元素。尝试此代码。
$(document).on("click",".foundLocation",function(){
$(this).val(locationName);
});