[英]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.