简体   繁体   English

jQuery vs Javascript单击

[英]jQuery vs Javascript click

I have read many topics how to handle Javascript's onclick vs Jquery;s .click(), but I can't figure out how to pass parameters using jQuery. 我已经阅读了许多主题如何处理Javascript的onclick与Jquery; s的.click(),但是我不知道如何使用jQuery传递参数。

1st option - Javascript, HTML 第一种选择-Javascript,HTML

The HTML

<input type="button" onclick="doAction(<?=$id?>,'order');" />

Therefore in JS I can do 因此在JS中我可以做

function doAction(id,type){

 //do something here

}

2nd option - jQuery,HTML 第二个选择-jQuery,HTML

The HTML

<input type="button" id="trigger" />

So jQuery becomes 所以jQuery成为

$("#trigger").click(function() {

   //do something here

 });

Do I have to do something like (in this case how do I know the values of id and type?) 我是否必须做类似的事情(在这种情况下,我如何知道id和type的值?)

  $("#trigger").click({id: "???", type: "????"}, other_function);

  function other_function(event){
     id = event.data.param1;
     type = event.data.param2;
   }

Do I have to "pass parameters" by using 我必须通过使用“传递参数”吗

  HTML
  <input type="hidden" id="id" value="<?=$id?>" />
  <input type="hidden" id="type" value="order" />

  jQuery

   $("#trigger").click(function(){
      var id = $("#id").val();
      var type = $("#type").val();
      //do something

   });

I want to avoid using onclick() as I have read that it should be avoided. 我想避免使用onclick(),因为我已经读过它应该避免。 I just need a suitable way to pass parameters as I did by using onclick(). 我只需要一种合适的方法来传递参数,就像使用onclick()一样。

You can use data to pass the data() to event. 您可以使用数据将data()传递给事件。

Live Demo 现场演示

 <input type="hidden" id="id" data-idatt="123" />
 <input type="hidden" id="type" value="order" />

 $("#trigger").click(function(){
    var id = $("#id").data("idatt").val();
 });

You don't need to take parameter from outside and don't need hidden field either 您不需要从外部获取参数,也不需要隐藏字段

$("#trigger").click(function(){
      var id = <?=$id?>;
      //do something
   });

using chrome open up the console and try this 使用chrome打开控制台并尝试

$(#trigger);
$(#trigger).click(function(e) {
  console.log(
               $(this),
               $(this).attr('type') 
             );
});

the function has a hidden variable called this and is the element you triggered the event. 该函数具有一个名为this的隐藏变量,并且是触发事件的元素。

$("#myElement").click({ "a": 1, "b": 2 }, function (e) {
    alert(e.data.a); // alerts 1
    alert(e.data.b); // alerts 2
});

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

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