我希望从html onClick事件中将参数传递给onClick jQuery函数。
PHP中的HTML语句呈现:
$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:
function callJSFunc(i , name){
alert(i+" "+name);
}
我想把它变成这样子:
$(".href").click(function(i,name,event){
alert(i+" "+name);
});
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
$(".href").click(function(){
alert($(this).attr('data-id')+" "+$(this).attr('data-name'));
});
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.
What I mean by using data-*
attributes is to store the data inside your DOM element:
<a class="href" data-index="$i" data-name="$name" href="someHref" />
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
});
It is better to do this with jQuery instead of sending the parameters with PHP.
You can do something like this in your 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'.