【发布时间】:2017-05-13 03:38:52
【问题描述】:
我想要做的是,将另一个文件(假设是 new_machine.php)中的输入表单加载到我的 index.php 中。在这种形式中,我有一个带有下拉列表的输入,它从 MySQL 数据库中获取选项并将它们列为锚点。这很好用。然后我想用 jQuery 的 .click() 方法控制用户的输入,所以当单击某个锚点时,我将能够获取它的文本并将其设置为下拉按钮的值。然而这并没有发生,因为似乎 jQuery 的动作没有被触发。所以我的问题是如何在我的 index.php 中加载的部分 .html/.php 中使用 jQuery。我的文件如下所示:
new_machine.php - 表单 - 我知道下拉菜单没有输入,我只想获取按钮中显示的文本,所以我知道 jQuery 可以工作。
<div class="tab-content">
... some text inputs
<label>
Purchase date<span class="req">*</span>
</label>
<input type="date" required="" />
<label>
Machine<span class="req">*</span>
</label>
<div class="dropdown">
<button id="chosenGroup" class="dropbtn">Choose machine</button>
<div class="dropdown-content" id="machineList" >
<?php
session_start();
try {
$bdd = new PDO('mysql:host=******:****; dbname=track', '*****', '*****');
} catch(Exception $e) {
exit('Unable to connect to db.');
}
$sql = "SELECT * FROM machinegroup WHERE UserID=:uid";
$q = $bdd->prepare($sql);
$q->bindParam(':uid', $_SESSION['valid_user']);
$q->execute();
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo "<a href=\"#\" class=\"machineGroupClick\">". $row['Name'] ."</a>";
}
?>
</div>
</div>
<script>
$(document).ready(function(){
$('.machineGroupClick').click(function(){
var name = $(this).html();
$( '#machine-content' ).text('lalal');
$('#chosenGroup').html(name);
});
});
</script>
</div>
index.php
<head>
...
<script src="https://code.jquery.com/jquery.js"></script>
<script src="machines/js/data.js"></script>
...
</head>
<body>
...
<a href="#" id="new-machine">...</a>
...
<div id="machine-content" class="col-md-9" style="float:right">
...
</body>
data.js(这是在我的 index.php 中处理点击和其他事件的 jQuery 脚本)
$('#new-machine').click(function(){
$( '#machine-content' ).load('new_machine.php');
});
我也曾尝试将 new_machine.php 中的 jQuery 代码放入 index.php 和 data.js 中,但它从未奏效。所以我的问题是加载部分 html/php 时使用 jQuery 的正确方法是什么?我错过了一些重要的东西吗?如果代码全部为 index.php 且未加载,则下拉菜单工作正常,但我希望它在用户单击“新机器”时加载到页面内。干杯
【问题讨论】:
-
在父index.php中
-
对于动态生成的元素使用on()方法绑定事件
标签: javascript php jquery html ajax