使用ajax我在下拉菜单中插入表行。它工作并显示它。我想在点击行时附加事件,但是,我尝试过的东西不起作用。可能是什么问题?
PHP
<?php
for($i=1; $i<=2; $i++){
echo "<div class='medium-block dropdown'>
<div class='dropdown-toggle stat-dropdown not-added' id='away" . $i . "' data-toggle='dropdown'>
<p class='vertical-center add-player' id='add-player" . $i . "' style='margin:0;'>Add Player</p>
</div>
<ul class='dropdown-menu drop-scroll' style='margin:0; padding:0; border-radius:0;'>
<table class='table table-hover' style='margin:0;'>
<tbody id='choose-player-away" . $i . "'>
</tbody>
</table>
</ul>
</div>";
}
for($i=3; $i<=5; $i++){
echo "<div class='medium-block dropup'>
<div class='dropdown-toggle stat-dropdown not-added' id='away" . $i . "' data-toggle='dropdown'>
<p class='vertical-center add-player' id='add-player" . $i . "' style='margin:0;'>Add Player</p>
</div>
<ul class='dropdown-menu drop-scroll' style='margin:0; padding:0; border-radius:0;'>
<table class='table table-hover' style='margin:0;'>
<tbody id='choose-player-away" . $i . "'>
</tbody>
</table>
</ul>
</div>";
}?>
JQuery的
<script type="text/javascript">
$(document).ready(function(){
scalability();
$(window).resize(scalability);
$(".not-added").each(function(i){
$(this).click(function(){
var identifier = $(this).attr('id').charAt(4);
var teamid = $(this).attr('id').substring(0,4);
if($(this).hasClass("not-added")){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("choose-player-"+teamid+identifier).innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getPlayerlist.php?team="+teamid+"&id="+identifier,true);
xmlhttp.send();
$(".player").on('click',function(){
alert("working");
});
}
});
});
});
</script>
由AJAX提取的PHP文件
<?php
$team = $_GET["team"];
$id = $_GET["id"];
$con = mysqli_connect('localhost','root','','sportacus');
$query = "SELECT * FROM " . $team . "_team WHERE incourt = 0 ORDER BY number";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)){
echo "<tr class='player' id='" . $team . "-player" . $row['id'] . "'>
<td>" . $row['number'] . "</td>
<td>" . $row['first_name'] . " " . $row['last_name'] . "</td>
</tr>";
}
mysqli_close($con);
?>
我希望可以点击由AJAX获取的php文件创建的类.player
的行。
注意:如果有帮助,我正在使用bootstrap库。其他一切都有效,除了部分:
$(".player").on('click',function(){
alert("working");
});
答案 0 :(得分:0)
与event binding on dynamically created elements中报告的一样,您需要委派活动。
在您的情况下,您需要更改:
$(".player").on('click',function(){
为:
$(document).on('click', ".player", function () {
alert("working");
});