我有兩個腳本在我的頁面上運行,它們自己工作,但不在一起工作。腳本的第一部分是一個ajax POST,它根據搜索從我的數據庫中選擇行。這全部在模式窗口中呈現。第二個腳本等待.btnSave ID內的點擊,關閉模式窗口並將該ID的值複製到表格的最後一行。.click函數在ajax中不工作
兩個JavaScript文件一起:
$(document).ready(function()
{
$('.btnSave').click(function() {
alert();
var value = this.id;
$('#tablemain tbody tr:last #itemlookup').val(value);
$('#tablemain tbody tr:last #itemlookup').focus();
$('#productlookup').modal('hide');
});
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
$.ajax(
{
url : "ajax.php",
type: "POST",
data : postData,
success:function(data)
{
$("#simple-msg").html(data);
}
});
e.preventDefault(); //STOP default action
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});
主要PHP文件包括模態窗口:
<div id="productlookup" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Instant Car Parts Stock Lookup</h4>
</div>
<div class="modal-body">
<div class="main-content">
<section class="with-table"><form name="ajaxform" id="ajaxform" action="ajax.php" method="POST">
<div id="simple-msg"></div><div class="vehilcle-form-sect">
<div class="col-lg-4 col-md-4 "><p align="center"><input type="text" name="vehicleid" placeholder="VehicleID/Search Below"></p></div>
<div class="col-lg-4 col-md-4">
<p align="center">
<input type="button" id="simple-post" value="Search" />
</p>
</div>
</div></form>
</section>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
最後的ajax.php(工作正常):
<?php include("../../config.php");
include('../../includes/session.php');
session_start(); ?>
<table class="datatable tablesort selectable paginate full" width="100%">
<tbody>
<?php
if ($_POST['make']) {
$breaker_id = $_SESSION['breaker_id'];
$Make = $_POST['make'];
$Model = $_POST['model'];
$Year = $_POST['year'];
$show=mysql_query("SELECT * FROM stock where breaker='$breaker_id' and Make='$Make' and Model='$Model' and (Year = '".$Year."' OR YearRange LIKE '%".$Year."%')");
}
if ($_POST['vehicleid']) {
$breaker_id = $_SESSION['breaker_id'];
$vehicleid = $_POST['vehicleid'];
$show=mysql_query("SELECT * FROM stock where breaker='$breaker_id' and VehicleID='$vehicleid' AND VehicleID!=''");
}
$xx = 1;
while($row=mysql_fetch_array($show)){
?>
<tr id="row_<?php echo $xx; ?>">
<td><strong class="btnSave" id="<?php echo $row['id']; ?>"><?php echo $row['id']; ?>
</strong>
<p><?php echo $row['stock_item']; ?> £<?php echo $row['price']; ?></p>
</td>
</tr><?php
$xx++;
} ?>
</tbody>
</table>
我假設這是因爲JavaScript無法識別.btnSave,因爲它是在ajax之後加載的?
你的推測是正確的。注入html片段需要在渲染後附加它們的事件。 – Daniel