Javascript 使用jquery在一行中进行简单的onclick

Javascript 使用jquery在一行中进行简单的onclick,javascript,jquery,Javascript,Jquery,在下面的代码中,我无法找出我做错了什么: <table width='100%'> <script>$("#101m").on("click", function() {alert($( this ).text());});</script> <tr id='101m'><td class='dayavailible'>A</td></tr> <script>$("#101a").on("cli

在下面的代码中,我无法找出我做错了什么:

<table width='100%'>

<script>$("#101m").on("click", function() {alert($( this ).text());});</script>
<tr id='101m'><td  class='dayavailible'>A</td></tr>

<script>$("#101a").on("click", function() {alert($( this ).text());});</script>
<tr id='101a'><td  class='dayavailible'>A</td></tr>

<script>$("#101e").on("click", function() {alert($( this ).text());});</script>
<tr id='101e'><td  class='dayavailible'>A</td></tr>
</table>

$(“#101m”)。在(“单击”,函数(){alert($(this.text());});
A.
$(“#101a”).on(“单击”,函数(){alert($(this.text());});
A.
$(“#101e”)。在(“单击”,函数(){alert($(this.text());});
A.

任何帮助都将不胜感激

您的脚本是在加载DOM之前执行的,因此元素还不存在,而jQuery选择器与任何内容都不匹配,因此没有元素会绑定到click处理程序。您需要使用in调用
init()
方法

在文档“就绪”之前,页面无法安全操作。jQuery会为您检测这种就绪状态。$(document).ready()中包含的代码只有在页面文档对象模型(DOM)准备好让JavaScript代码执行后才会运行


或者,将脚本移动到页面末尾的
标记之前。

您的onclick事件无法绑定到所有行,因为在脚本出现时HTML中没有元素,所以可以将JavaScript代码移动到HTML之后,或者使用
$(function(){…})DOM就绪

尽管我建议您使用模块化代码,这样您就不必一次又一次地编写相同的代码

<script>
// DOM Ready
$(function(){
  $("[id*='101']").on("click", function() {
     alert($( this ).text());
  });
});
</script>

//DOM就绪
$(函数(){
$(“[id*='101']”)。在(“单击”,函数()上){
警报($(this.text());
});
});

在元素存在之前附加事件处理程序。将所有脚本放在页面末尾、
之前或文档中的单个脚本中。在
中的ready处理程序就像在订购比萨饼之前等待比萨饼一样。。。作为sdie not,HTML标记无效,将脚本标记作为表的子级
<script>
// DOM Ready
$(function(){
  $("[id*='101']").on("click", function() {
     alert($( this ).text());
  });
});
</script>