javascript 从 html onclick 事件传递 jQuery onclick 函数的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14278699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing parameter on jQuery onclick function from html onclick event
提问by sourcecode
I want to pass parameters to onclick jquery function from html onclick event.
我想从 html onclick 事件将参数传递给 onclick jquery 函数。
html statement rendering in PHP
html 语句在 PHP 中的呈现
$name = "abcd";
for ($i=0;$<10;$i++){
$text .= '<tr>
<td>'.$i.'</td>
<td><div id="name">'.$name.'/div>
<a class="href" onclick="callJSFunc($i,\''.$name.'\')" ></a>
</td>
</tr>';
}
javascript..
javascript..
function callJSFunc(i , name){
alert(i+" "+name);
}
I want to convert it into someting...
我想把它转换成...
$(".href").click(function(i,name,event){
alert(i+" "+name);
});
回答by Irfan DANISH
Why don't you try in some other way
你为什么不试试其他方式
$name = "abcd";
for ($i=0;$<10;$i++){
$text .= '<tr>
<td>'.$i.'</td>
<td><div id="name">'.$name.'/div>
<a class="href" data-id="'.$i.'" data-name="'.$name.'" ></a>
</td>
</tr>';
}
And in jQuery onClick
在 jQuery onClick 中
$(".href").click(function(){
alert($(this).attr('data-id')+" "+$(this).attr('data-name'));
});
回答by Konstantin Dinev
You cannot change the way events are fired but you can always store those parameters as data-*
attributes in markup and extract them inside the event handler. What you request is to subscribe for the event and the event object to naturally mutate according to what you desire as parameters, however the browser has no way to figure out what you require.
您无法更改触发事件的方式,但您始终可以将这些参数作为data-*
属性存储在标记中,并在事件处理程序中提取它们。您请求的是订阅事件和事件对象以根据您想要的参数自然变化,但是浏览器无法弄清楚您需要什么。
What I mean by using data-*
attributes is to store the data inside your DOM element:
我使用data-*
属性的意思是将数据存储在 DOM 元素中:
<a class="href" data-index="$i" data-name="$name" href="someHref" />
jQuery:
jQuery:
$('.href').click(function (event) {
var index = $(this).attr('data-index'); // Yields a string use data() for other data types
var name = $(this).attr('data-name'); // Yields a string use data() for other data types
});
回答by Anton Timmermans
It is better to do this with jQuery instead of sending the parameters with PHP.
最好使用 jQuery 来执行此操作,而不是使用 PHP 发送参数。
You can do something like this in your javascript:
你可以在你的javascript中做这样的事情:
$('a.href').click(function( event ) {
var index = $('table').index(this); // Containing table
var name = $(this).siblings('#name').innerHTML;
alert( index + ' ' + name );
});
Btw, an id should be unique. Your code generates 10 table rows with in every one of them the id '#name'.
顺便说一句,一个 id 应该是唯一的。您的代码生成 10 个表行,其中每一行的 ID 为“#name”。