使用 HTML 按钮调用 JavaScript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1947263/
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-08-22 22:01:22  来源:igfitidea点击:

Using an HTML button to call a JavaScript function

javascripthtml

提问by forrest

I am trying to use an HTML button to call a JavaScript function.

我正在尝试使用 HTML 按钮调用 JavaScript 函数。

Here's the code:

这是代码:

<input type="button" value="Capacity Chart" onclick="CapacityChart();">

It doesn't seem to work correctly though. Is there a better way to do this?

虽然它似乎不能正常工作。有一个更好的方法吗?

Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.htmlclick on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.

这是链接:http: //projectpath.ideapeoplesite.com/bendel/toolscalculators.html单击左下角的容量选项卡。如果值未更改,该按钮应生成警报,如果您输入值,则应生成图表。

回答by Andy E

There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.

有几种方法可以使用 HTML/DOM 处理事件。没有真正正确或错误的方式,但不同的方式在不同的情况下是有用的。

1: There's defining it in the HTML:

1:在HTML中定义它:

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />

2: There's adding it to the DOM property for the event in Javascript:

2:在Javascript中将其添加到事件的DOM属性中:

//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;

//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };

3: And there's attaching a function to the event handler using Javascript:

3:使用Javascript将函数附加到事件处理程序:

var el = document.getElementById("clickMe");
if (el.addEventListener)
    el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
    el.attachEvent('onclick', doFunction);

Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.

第二种和第三种方法都允许内联/匿名函数,并且都必须在从文档中解析元素后声明。第一种方法不是有效的 XHTML,因为 onclick 属性不在 XHTML 规范中。

The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.

第一个和第二个方法是互斥的,这意味着使用一个(第二个)将覆盖另一个(第一个)。第 3 种方法将允许您将任意数量的函数附加到同一个事件处理程序,即使也使用了第一种或第二种方法。

Most likely, the problem lies somewhere in your CapacityChart()function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:

很可能,问题出在您的CapacityChart()函数中。访问您的链接并运行您的脚本后,CapacityChart() 函数将运行并打开两个弹出窗口(一个根据脚本关闭)。你有以下几行:

CapacityWindow.document.write(s);

Try the following instead:

请尝试以下操作:

CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();

EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.allwith document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.

编辑
当我看到你的代码时,我以为你是专门为 IE 编写的。正如其他人所说,你将需要更换引用document.alldocument.getElementById。但是,在此之后您仍然有修复脚本的任务,因此我建议至少首先让它在 IE 中工作,因为您在更改代码以跨浏览器工作时犯的任何错误都可能导致更多的混乱。一旦它在 IE 中工作,当您更新代码时,更容易判断它是否在其他浏览器中工作。

回答by Paul

I would say it would be better to add the javascript in an un-obtrusive manner...

我会说以不引人注目的方式添加javascript会更好......

if using jQuery you could do something like:

如果使用 jQuery,您可以执行以下操作:

<script>
  $(document).ready(function(){
    $('#MyButton').click(function(){
       CapacityChart();
    });
  });
</script>

<input type="button" value="Capacity Chart" id="MyButton" >

回答by Jeff

Your HTML and the way you call the function from the button look correct.

您的 HTML 和您从按钮调用函数的方式看起来是正确的。

The problem appears to be in the CapacityCountfunction. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.

问题似乎出在CapacityCount函数中。我在 Firefox 3.5 的控制台中收到此错误:“document.all 未定义”在 bendelcorp.js 的第 759 行。

Edit:

编辑:

Looks like document.allis an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").valueinstead of document.all.Capacity.RUnits.value

看起来document.all是 IE-only 的东西,是访问 DOM 的非标准方式。如果您使用document.getElementById(),它应该可以工作。示例:document.getElementById("RUnits").value代替document.all.Capacity.RUnits.value

回答by jitter

This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code

这看起来是正确的。我猜您使用不同的名称或在按钮不可见的上下文中定义了您的函数。请添加一些代码

回答by Hymani

Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.

正如您所知,当您调用该函数时,分号 ( ;) 不应该出现在按钮中。

So it should just look like this: onclick="CapacityChart()"

所以它应该看起来像这样: onclick="CapacityChart()"

then it all should work :)

那么一切都应该有效:)

回答by textmonster404

I have an intelligent function-call-backing button code:

我有一个智能功能回调按钮代码:

<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>

回答by Patricia

Your code is failing on this line:

您的代码在这一行失败:

var RUnits = Math.abs(document.all.Capacity.RUnits.value);

i tried stepping though it with firebug and it fails there. that should help you figure out the problem.

我试着用萤火虫踩它,但它在那里失败了。这应该可以帮助您找出问题所在。

you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.

你有 jquery 引用。您不妨在所有这些功能中使用它。它会显着清理您的代码。

回答by NickFitz

One major problem you have is that you're using browser sniffing for no good reason:

您遇到的一个主要问题是您无缘无故地使用浏览器嗅探:

if(navigator.appName == 'Netscape')
    {
      vesdiameter  = document.forms['Volume'].elements['VesDiameter'].value;
      // more stuff snipped
    }
    else
    {
      vesdiameter  = eval(document.all.Volume.VesDiameter.value);
      // more stuff snipped
    }

I'm on Chrome, so navigator.appNamewon't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?

我在 Chrome 上,所以navigator.appName不会Netscape。Chrome 支持document.all吗?也许,但话又说回来,也许不是。其他浏览器呢?

The version of the code on the Netscapebranch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a nameattribute on the inputelements, so they won't be added to the form's elementsarray as named elements:

Netscape从 1996 年回到 Netscape Navigator 2,分支上的代码版本应该可以在任何浏览器上正常工作,所以你可能应该坚持下去......除了它不起作用(或不能保证工作) 因为您没有nameinput元素上指定属性,所以它们不会elements作为命名元素添加到表单的数组中:

<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">

Either give them a name and use the elementsarray, or (better) use

要么给他们一个名字并使用elements数组,要么(更好)使用

var vesdiameter = document.getElementById("VesDiameter").value;

which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementByIdsupport:

这将适用于所有现代浏览器 - 无需分支。为了安全起见,将浏览器版本大于或等于 4 的嗅探替换为getElementById支持检查:

if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
    // do stuff...
}

You probably want to validate your input as well; something like

您可能还想验证您的输入;就像是

var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
    alert("Diameter should be numeric");
    return;
}

would help.

有助于。

回答by AGrush

SIMPLE ANSWER:

简单的答案:

   onclick="functionName(ID.value);

Where ID is the ID of the input field.

其中 ID 是输入字段的 ID。

回答by erenon

silly way:

愚蠢的方式:

onclick="javascript:CapacityChart();"

You should read about discrete javascript, and use a frameworks bind method to bind callbacks to dom events.

您应该阅读离散 javascript,并使用框架绑定方法将回调绑定到 dom 事件。