问题描述
|
在PHP页面中,一个表有几行,像这样
echo \'<tr><td><a href=\"#\" onclick=\"myFunction(\'.$id.\')\">Click</a></td></tr>\';
ѭ1是从数据库动态生成的
所以我想在jQuery中定义函数,但要将参数传递给jQuery函数。
对于我单击的每个按钮,将传递另一个参数
解决方法
为什么不使用ID作为链接的标识符,如下所示:
<a href=\"#\" id=\"<?=$id?>\" class=\"myjquerylink\">Click me</a>
在jQuery中,您可以像这样绑定到onclick事件:
//加载时执行
$(document).ready(function(){
//绑定点击
$(\'a.myjquerylink \')。click(function(){
//获取ID
var id = $(this).attr(\'id \');
//用id做某事。
doSomething(id);
});
});
, 您到底想做什么?
这是一个示例函数(它没有使用jQuery!),以警告用户链接已被按下并停止传播该事件,从而使该事件不会在单击时跳转到另一页
<script type=\"text/javascript\">
function myFunction( param ) {
alert(\'The button with the id \' + param + \' has been pressed!\');
return false;
}
</script>
, 好吧,您可以通过以下方式在rel标签中分配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 \')。bind(\'click \',function(){
this.preventDefault();
alert($(this.attr(\“ 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())});