在PHP页面我有这样发送参数到jQuery函数
echo '<tr><td><a href="#" onclick="myFunction('.$id.')">Click</a></td></tr>';
的$id
一个表中的几行被动态地从数据库中生成
所以我要定义的jQuery的功能,但将参数传递给jQuery函数。
对于每一个按钮,我点击会有通过
在PHP页面我有这样发送参数到jQuery函数
echo '<tr><td><a href="#" onclick="myFunction('.$id.')">Click</a></td></tr>';
的$id
一个表中的几行被动态地从数据库中生成
所以我要定义的jQuery的功能,但将参数传递给jQuery函数。
对于每一个按钮,我点击会有通过
为什么不使用ID为这样的链接标识另一个参数:
<a href="#" id="<?=$id?>" class="myjquerylink">Click me</a>
在jQuery中可以绑定到像onclick事件这样的:
// Execute on load $(document).ready(function(){ // Bind to click $('a.myjquerylink').click(function(){ // Get the id var id = $(this).attr('id'); // Do something with the id. doSomething(id); }); });
您需要修改HTML一点:
echo '<tr><td><a class="someclass" href="#" id='".$id.'">Click</a></td></tr>';
然后你可以通过它在JQuery中的类来调用它,并做你想做的事: “$(this)”将是对被点击项的引用。
$(".someclass").live('click',function(e){ e.preventDefault(); alert($(this).text())});
你究竟想干什么?
下面是一个示例功能(它不使用jQuery!),提醒该链接已被按下,并停止传播事件的用户,所以它不会跳转到另一个页面上点击
<script type="text/javascript">
function myFunction(param) {
alert('The button with the id ' + param + ' has been pressed!');
return false;
}
</script>
好在一个肮脏的方式,你可以指定你的ID在相对标签是这样的:
echo '<tr><td><a href="#" rel="'.$id.'" class="mylink">Click</a></td></tr>';
比你可以在jQuery的搜索则myButton类的事件添加到它:
$("a.mylink").click(function(){
alert($(this).attr('rel'));
});
所以在这种情况下$(this).attr('rel')应该是你的ID。
正如其他海报开始说的,绑定一个功能到一个事件。假设你分配一个CSS类的一个标签,使其更容易:
echo '<tr><td><a class="specialLinks" href="#" onclick="myFunction('.$id.')">Click</a></td></tr>';
那么你会绑定到你的类是这样的:
$(“ specialLink‘)绑定(’点击”,功能(){ this.preventDefault(); 警报($(this.attr( “ID”)); });
的''不会有'val'虽然属性... – 2011-05-30 21:33:15
这里有一个错字:'href =“#”id ='。$ id。'“>点击' – tXK 2011-05-30 21:34:56
thx,我修正了错字,并改为val()to t ext() - 我刚刚从随机源代码中复制。 – balint 2011-05-30 21:38:59