我无法得到警报.我错过了什么?

Sco*_*t B 2 php jquery

我无法得到警报.我错过了什么?(以下代码在WP插件中)

<?php
wp_enqueue_script('jquery');
?>
<script type="text/javascript">
    jQuery('#myTest').click(function(){alert('hi');});
</script>
<?php
    echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
Run Code Online (Sandbox Code Playgroud)

And*_*y E 9

脚本在元素之前处理,因此#myTest在分配处理程序时不存在.交换它们:

<?php
    echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
<script type="text/javascript">
    jQuery('#myTest').click(function(){alert('hi');}));
</script>
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用live(),它允许将事件绑定到尚不存在的元素:

<script type="text/javascript">
    jQuery('#myTest').live("click", function(){alert('hi');}));
</script>
<?php
    echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
Run Code Online (Sandbox Code Playgroud)

或者使用jQuery的ready()处理程序,它将在解析所有元素时触发:

<script type="text/javascript">
    jQuery(document).ready(function ($) { 
        $('#myTest').click(function(){alert('hi');}));
    });
</script>
<?php
    echo "<div><input type='button' value='Test' id='myTest' /></div>";
?>
Run Code Online (Sandbox Code Playgroud)

请注意,在最后一个示例中,我在$传递给函数的参数中对jQuery命名空间进行别名.这允许您使用$WordPress的jQuery而不是一直输入jQuery.