简体   繁体   English

从html onclick事件传递jQuery onclick函数的参数

[英]passing parameter on jQuery onclick function from html onclick event

I want to pass parameters to onclick jquery function from html onclick event. 我想从html onclick事件中将参数传递给onclick jquery函数。

html statement rendering in PHP 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.. 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 并在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. 您无法更改触发事件的方式,但您始终可以将这些参数作为data-*属性存储在标记中,并在事件处理程序中提取它们。 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: 我使用data-*属性的意思是将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
});

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. 顺便说一下,id应该是唯一的。 Your code generates 10 table rows with in every one of them the id '#name'. 您的代码生成10个表行,每个表中都有id'#name'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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