使用jquery进行多表警报

时间:2011-12-17 06:53:24

标签: php javascript jquery html

我有以下内容:

$columns = array('aaa','bbb','ccc','ddd');
$num_cols = count(columns);
echo "<table>";
echo "<tr>";
foreach($columns as $col)
{
   echo "<td>$col</td>";
}
echo "</tr>";

for($i=1;$i<4;$i++)
{
   echo "<tr>";
   for($j=0;$j<$num_cols;$j++)
   {
      echo "<td class='click' from=???>$i</td>";
   }
   echo "</tr>";
}

echo "</table>";

这为我生成了:

aaa | bbb | ccc | ddd
 1  |  1  |  1  |  1 
 2  |  2  |  2  |  2 
 3  |  3  |  3  |  3

我想添加此警报jquery - 如果我点击例如 2来自aaa 我已收到警报(2来自a);

我使用jquery:

$(".click").click(function(){
   alert($(this).html + "from" + ???);
})

这可能吗?

2 个答案:

答案 0 :(得分:1)

首先请注意html是一个函数。此外,on是从jQuery 1.7开始添加事件的首选方法

我会将标题单元格放在<th>标记中,然后执行:

$(document).on("click", "td", function () {
     var index = $(this).parent().find(this).index();
     alert($(this).html() + "from" + $("table th").eq(index).html());
});

这是fiddle


或者,如果您不想将第一行放在<th>标记中,这也会有效:

$(document).on(“click”,“td”,function(){         var index = $(this).parent()。find(this).index();        alert($(this).html()+“from”+ $(“table tr:first td”)。eq(index).html());    });

更新了fiddle

答案 1 :(得分:0)

最好使用jQuery live

来使用它
$(".click").live("click", function(){
   alert($(this).html + "from" + ???);
})