简体   繁体   中英

passing parameter on jQuery onclick function from html onclick event

I want to pass parameters to onclick jquery function from html onclick event.

html statement rendering in 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..

function callJSFunc(i , name){
alert(i+"  "+name);
}

I want to convert it into someting...

$(".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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM