javascript 将参数从链接 onclick 传递给 JS 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6287172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:10:28  来源:igfitidea点击:

Passing argument to JS function from link onclick

javascriptajaxclosures

提问by Genadinik

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. Any idea why this happens and how to fix this? :)

但是进来的值是 [object MouseEvent],而不是我期望的数字。知道为什么会发生这种情况以及如何解决这个问题吗?:)

Thanks!

谢谢!

回答by ErikE

You are trying to assign the function to your link in two different and conflicting ways.

您正试图以两种不同且相互冲突的方式将该功能分配给您的链接。

Using the eval-ed function string, onclick = "function(value)", works but is deprecated.

使用 eval-ed 函数字符串onclick = "function(value)", 可以工作,但已弃用。

The other way of binding the click handler in the onloadevent 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 onclickis completely lost when you set the onclickto a new function.

onload事件中绑定点击处理程序的另一种方法也适用,但如果您希望传递特定值,则必须稍微更改脚本,因为在onclick设置onclick到一个新功能。

To make your current method work, you don't need an onloadhandler at all. You just need this:

要使您当前的方法工作,您根本不需要onload处理程序。你只需要这个:

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). It is nothing in IE (thus the need to also grab window.event). I added a little helper function for you that creates a closure around your parameter value. 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.

DOM 事件函数的参数是事件对象(在 Firefox 和其他符合标准的浏览器中)。它在 IE 中什么都不是(因此还需要抓取 window.event)。我为您添加了一个小辅助函数,它可以围绕您的参数值创建一个闭包。你可以自己每次都这样做,但这会很痛苦。最重要的部分是,getcall的是,一个函数返回一个函数,而正是这种返回功能,当您单击的元素被调用。

Finally, I recommend strongly that instead of all this, you use a library such as jQuerybecause 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 onloadevent fires with the simulated event ready. 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 onloadand it is a reallyhard problem to solve cross-browser.
  • Dealing with how the event object is being passed
  • Figuring out all the different ways that browsers handle things like event propagation and getting the clicked item and so on.
  • 单个事件有多个处理程序
  • onload使用模拟事件触发事件之前尽快运行 JavaScript ready。例如,也许图像仍在下载,但您想在用户尝试使用该页面之前将焦点放在控件上,您不能这样做,onload并且跨浏览器是一个非常困难的问题。
  • 处理如何传递事件对象
  • 找出浏览器处理事件传播和获取点击项目等事情的所有不同方式。

Note: in your click handler you can just use the thisevent which will have the clicked element in it. This could be really powerful for you, because instead of having to encode which item it was in the JavaScript for each element's onclickevent, you can simply bind the same handler to all your items and get its value from the element. This is better because it lets you encode the information about the element only in the element, rather than in the element andthe JavaScript.

注意:在您的点击处理程序中,您可以只使用this其中包含被点击元素的事件。这对您来说可能非常强大,因为您不必为每个元素的onclick事件在 JavaScript 中编码哪个项目,您只需将相同的处理程序绑定到所有项目并从元素中获取其值。这更好,因为它允许您仅在元素中编码有关元素的信息,而不是在元素JavaScript 中编码。

回答by rsbarro

You should just be able to declare the function like this (no need to assign on window.onload):

您应该能够像这样声明函数(无需分配 on window.onload):

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

回答by Alan Ortego

The first parameter in javascript event is the event itself. If you need a reference back to the "a" tag you could use the thisvariable because the scope is now the "a" tag.

javascript 事件中的第一个参数是事件本身。如果您需要引用回“a”标签,您可以使用this变量,因为范围现在是“a”标签。

回答by user2704136

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 eventis defined in the JavaScript environment when the onclick handler is called.

此代码之所以有效,event是因为它是在调用 onclick 处理程序时在 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 的替代形式,具有相同的效果:

<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/>

回答by basicxman

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 MouseEventas it's an onclickevent) as the first argument.

当您像这样为 DOM 元素上的事件分配一个函数时,浏览器会自动将事件对象(在这种情况下,MouseEvent因为它是一个onclick事件)作为第一个参数传递。

Try it like this,

像这样试试,

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