gpt4 book ai didi

JavaScript/JQuery 在加载了 load() 的 html 中不起作用

转载 作者:行者123 更新时间:2023-11-30 16:01:05 26 4
gpt4 key购买 nike

我想做的是,从另一个文件(假设是 new_machine.php)加载一个输入表单到我的 index.php。在这种形式中,我有一个带有下拉列表的输入,它从 MySQL 数据库中获取选项并将它们列为 anchor 。这很好用。然后我想用 jQuery 的 .click() 方法控制用户的输入,所以当单击某个 anchor 时,我将能够获取它的文本并将其设置为下拉按钮的值。然而,这并没有发生,因为似乎没有触发 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>

索引.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 且未加载,则下拉列表工作正常,但我希望它在用户单击“新机器”时加载到页面内。干杯

最佳答案

data.js 应该是这样的:

$(document).ready(function(){
$('#machine-content').on('click','.machineGroupClick',function(){//use event delegation here because your html is in the partial and it is loaded after the dom ready
var name = $(this).html();
$( '#machine-content' ).text('lalal');
$('#chosenGroup').html(name);
});
$('#new-machine').click(function(){
$( '#machine-content' ).load('new_machine.php');
});
});

关于JavaScript/JQuery 在加载了 load() 的 html 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37745960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com