[英]Jquery is not working on html echoed by php
我使用php在体内echo
html。 像这样:
<body>
<?php
echo " <button type=\"button\" id=\"button\">Click Me!</button> ";
?>
</body>
在此html中,我有一个ID设置为button
。 然后,在Jquery中,我有以下代码:
$(document).ready(function(){
$("#button").click(function(){
alert("It works");
});
});
但是, 它没有得到打印。 我该怎么办?
它还取决于您的Javascript代码在DOM中的位置,以及是否在相关页面中包含jQuery。
像这样的东西有望工作:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<title>Demo</title>
</head>
<body>
<div class="container">
<?php
echo " <button type=\"button\" id=\"button\">Click Me!</button> ";
?>
</div>
<script type="text/javascript">
(function ($) {
$(document).ready(function(){
$("#button").on("click", function(e){
alert("It works");
});
});
})(jQuery);
</script>
</body>
</html>
请注意,以上代码段假定位于PHP文件中(例如,index.php)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.