简体   繁体   English

从链接 onclick 将参数传递给 JS function

[英]Passing argument to JS function from link onclick

I have a link that looks like this:我有一个看起来像这样的链接:

<a id="mylink" onclick="deleteHike( 3 );" href="javascript:void(0);">Yes</a>

It is able to call this JavaScript:它可以调用这个 JavaScript:

window.onload = function()
{

  //Get a reference to the link on the page
  // with an id of "mylink"
  var a = document.getElementById("mylink");

  //Set code to run when the link is clicked
  // by assigning a function to "onclick"
  a.onclick = function( hike_id )
  {
     // Somecode her
     // But when I try to use the hike_id it displays as [object MouseEvent] 
  }
}

But the value that comes in is [object MouseEvent], not the number that I was expecting.但是进来的值是 [object MouseEvent],而不是我期望的数字。 Any idea why this happens and how to fix this?知道为什么会发生这种情况以及如何解决这个问题吗? :) :)

Thanks!谢谢!

You are trying to assign the function to your link in two different and conflicting ways.您正在尝试以两种不同且相互冲突的方式将 function 分配给您的链接。

Using the eval-ed function string, onclick = "function(value)" , works but is deprecated.使用经过评估的 function 字符串onclick = "function(value)"可以工作,但已弃用。

The other way of binding the click handler in the onload event works too, but if you want a particular value to be passed, you'll have to change your script a bit because the value as given in the initial onclick is completely lost when you set the onclick to a new function.onload事件中绑定单击处理程序的另一种方法也可以,但是如果您希望传递特定值,则必须稍微更改脚本,因为初始onclick中给出的值在您完全丢失时将onclick设置为新的 function。

To make your current method work, you don't need an onload handler at all.要使您当前的方法工作,您根本不需要onload处理程序。 You just need this:你只需要这个:

function deleteHike(hike_id) {
   // Some code here
}

To do it the second way, which I recommend, it would look like this:我推荐第二种方式,它看起来像这样:

<a id="mylink" href="javascript:void(0);">Yes</a>

with this script:使用此脚本:

function deleteHike(e, hike_id) {
   // Some code here
   // e refers to the event object which you can do nifty things with like
   //  - learn the actual clicked element if it was a parent or child of the `this` element
   //  - stop the event from bubbling up to parent items
   //  - stop the event from being captured by child items
   //   (I may have these last two switched)
}

function getCall(fn, param) {
   return function(e) {
      e = e || window.event;
      e.preventDefault(); // this might let you use real URLs instead of void(0)
      fn(e, param);
   };
}

window.onload = function() {
   var a = document.getElementById("mylink");
   a.onclick = getCall(deleteHike, 3);
};

The parameter of a DOM event function is the event object (in Firefox and other standards-compliant browsers). DOM 事件 function 的参数是事件 object(在 Firefox 和其他符合标准的浏览器中)。 It is nothing in IE (thus the need to also grab window.event).在 IE 中什么都不是(因此还需要抓取 window.event)。 I added a little helper function for you that creates a closure around your parameter value.我为您添加了一个小帮手 function ,它围绕您的参数值创建了一个闭包。 You could do that each time yourself but it would be a pain.您可以每次都自己这样做,但这会很痛苦。 The important part is that getCall is a function that returns a function , and it is this returned function that gets called when you click on the element.重要的部分是 getCall 是一个 function ,它返回一个 function ,当您单击元素时,它返回的就是这个返回的 function 。

Finally, I recommend strongly that instead of all this, you use a library such as jQuery because it solves all sorts of problems for you and you don't have to know crazy JavaScript that takes much expertise to get just right, problems such as:最后,我强烈建议您使用jQuery之类的库来代替所有这些,因为它可以为您解决各种问题,而且您不必知道疯狂的 JavaScript 需要很多专业知识才能正确解决问题,例如:

  • Having multiple handlers for a single event单个事件有多个处理程序
  • Running JavaScript as soon as possible before the onload event fires with the simulated event ready .在模拟事件readyonload事件触发之前尽快运行 JavaScript 。 For example, maybe an image is still downloading but you want to put the focus on a control before the user tries to use the page, you can't do that with onload and it is a really hard problem to solve cross-browser.例如,也许一个图像仍在下载,但你想在用户尝试使用页面之前将焦点放在控件上,你不能通过onload做到这一点,而且解决跨浏览器是一个非常困难的问题。
  • Dealing with how the event object is being passed处理如何传递事件 object
  • Figuring out all the different ways that browsers handle things like event propagation and getting the clicked item and so on.找出浏览器处理事件传播和获取点击项目等事情的所有不同方式。

Note: in your click handler you can just use the this event which will have the clicked element in it.注意:在您的点击处理程序中,您可以只使用this事件,该事件将在其中包含被点击的元素。 This could be really powerful for you, because instead of having to encode which item it was in the JavaScript for each element's onclick event, you can simply bind the same handler to all your items and get its value from the element.这对您来说可能非常强大,因为不必为每个元素的onclick事件编码 JavaScript 中的哪个项目,您可以简单地将相同的处理程序绑定到所有项目并从元素中获取其值。 This is better because it lets you encode the information about the element only in the element, rather than in the element and the JavaScript.这更好,因为它允许您仅在元素中编码有关元素的信息,而不是在元素JavaScript 中。

The first parameter in javascript event is the event itself. javascript 事件中的第一个参数是事件本身。 If you need a reference back to the "a" tag you could use the this variable because the scope is now the "a" tag.如果您需要对“a”标签的引用,您可以使用this变量,因为 scope 现在是“a”标签。

You should just be able to declare the function like this (no need to assign on window.onload ):您应该能够像这样声明 function (无需在window.onload上分配):

function deleteHike(hike_id)
{
     // Somecode her
     // But when I try to use the hike_id it displays as [object MouseEvent] 
}

Here's my new favorite way to solve this problem.这是我最喜欢的解决这个问题的新方法。 I like this approach for its clarity and brevity.我喜欢这种方法,因为它清晰简洁。

Use this HTML:使用这个 HTML:

<a onclick="deleteHike(event);" hike_id=1>Yes 1</a><br/>
<a onclick="deleteHike(event);" hike_id=2>Yes 2</a><br/>
<a onclick="deleteHike(event);" hike_id=3>Yes 3</a><br/>

With this JavaScript:有了这个 JavaScript:

function deleteHike(event) {
    var element = event.target;
    var hike_id = element.getAttribute("hike_id");
    // do what you will with hike_id
    if (confirm("Delete hike " + hike_id + "?")) {
        // do the delete
        console.log("item " + hike_id + " deleted");
    } else {
        // don't do the delete
        console.log("user canceled");
    }
    return;
}

This code works because event is defined in the JavaScript environment when the onclick handler is called.此代码有效,因为在调用 onclick 处理程序时, event是在 JavaScript 环境中定义的。

For a more complete discussion (including why you might want to use "data-hike_id" instead of "hike_id" as the element attribute), see: How to store arbitrary data for some HTML tags .有关更完整的讨论(包括为什么您可能要使用“data-hike_id”而不是“hike_id”作为元素属性),请参阅: 如何为某些 HTML 标签存储任意数据

These are alternate forms of the HTML which have the same effect:这些是 HTML 的替代 forms 具有相同的效果:

<a onclick="deleteHike(event);" hike_id=4 href="javascript:void(0);">Yes 4</a><br/>
<button onclick="deleteHike(event);" hike_id=5>Yes 5</button><br/>
<span onclick="deleteHike(event);" hike_id=6>Yes 6</span><br/>

When you assign a function to an event on a DOM element like this, the browser will automatically pass the event object (in this case MouseEvent as it's an onclick event) as the first argument.当您将 function 分配给这样的 DOM 元素上的事件时,浏览器将自动将事件 object (在本例中为MouseEvent ,因为它是一个onclick事件)作为第一个参数。

Try it like this,试试这样

a.onclick = function(e, hike_id) { }

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

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