Javascript:如何获取点击按钮的innerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25004823/
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
Javascript: How to get innerHTML of clicked button
提问by Brian
Built a tip calculator but want to shorten the code by getting the innerHTML of the button that is being clicked.
构建了一个小费计算器,但希望通过获取正在单击的按钮的 innerHTML 来缩短代码。
Total Bill: <input id="bill" type="text">
<button type="button" onclick="tip15()">15</button>
<button type="button" onclick="tip18()">18</button>
<button type="button" onclick="tip20()">20</button>
<div id="tip">You owe...</div>
function tip15(){
var totalBill = document.getElementById("bill").value;
var totalTip = document.onclick.innerHTML
var tip = totalBill * 0.15;
document.getElementById("tip").innerHTML = "$" +tip
}
Problem with this method is that I have to write out three versions of the function to correspond with the tip amount. I want to create one function that grabs the innerHTML of the button being clicked and uses that value in the function. I want it to look something like this
这种方法的问题是我必须写出三个版本的函数来对应小费金额。我想创建一个函数来获取被点击的按钮的 innerHTML 并在函数中使用该值。我希望它看起来像这样
function tip(){
var totalBill = document.getElementById("bill").value;
**var totalTip = GET INNERHTML OF CLICKED BUTTON**
var tip = totalBill * ("." + totalTip);
document.getElementById("tip").innerHTML = "$" +tip
}
That way I can run the same function on the different buttons.
这样我就可以在不同的按钮上运行相同的功能。
回答by Muhammad Ashikuzzaman
Change like this:Pass value to tip function.
更改如下:将值传递给提示功能。
<button id="15" type="button" onclick="tip(15)">15</button>
<button id="18" type="button" onclick="tip(18)">18</button>
<button id="20" type="button" onclick="tip(20)">20</button>
function tip(tip_value)
{
/*use here tip_value as you wish you can use if condition to check the value here*/
var totalBill = document.getElementById("bill").value;
var totalTip = tip_value;
var tip = totalBill * ("." + totalTip);
document.getElementById("tip").innerHTML = "$" +tip;
}
回答by Jeff
Pass this.innerHTML
as an argument to your tip function.
this.innerHTML
作为参数传递给您的提示函数。
So your tip function should look like this:
所以你的提示函数应该是这样的:
function tip(totalTip) {
var totalBill = document.getElementById("bill").value;
var tip = totalBill * ("." + totalTip);
document.getElementById("tip").innerHTML = "$" +tip
}
Therefore, if you have a button element that looks like this:
因此,如果您有一个如下所示的按钮元素:
<button type="button" onclick="tip(this.innerHTML)">15</button>
The tip function will be called as tip(15)
.
tip 函数将被调用为tip(15)
.
回答by Mario Lopez
Use HTML5 data attributes.
使用 HTML5 数据属性。
<button type="button" data-tip="15" onclick="getTip(this)">15</button>
The parameter this
that you're passing to the function refers to the button that is being clicked. Then you get the value of the attribute like this:
this
您传递给函数的参数是指正在单击的按钮。然后你得到属性的值是这样的:
function tip(button){
var tip= button.getAttribute("data-tip");
...
}
I leave the rest for you.
我把剩下的留给你。
回答by Sebastien Daniel
I'll write up a quick solution, then explain why I did it that way.
我会写一个快速的解决方案,然后解释我为什么这样做。
PROPOSED SOLUTION
建议的解决方案
Part 1, the HTML
第 1 部分,HTML
<div id="tip-wrapper">
<label for="bill">Total bill:</label>
<input name="bill" id="bill" type="text">
<br/>
<label for="tipratio">Tip ratio:</label>
<button name="tipratio" value="15" type="button">15%</button>
<button name="tipratio" value="18" type="button">18%</button>
<button name="tipratio" value="20" type="button">20%</button>
<div id="final-value">You owe...</div>
</div>
Part 2, the JavaScript
第 2 部分,JavaScript
var parent = document.getElementById('tip-wrapper'),
buttons = parent.getElementsByTagName('button'),
max = buttons.length,
i;
// function that handles stuff
function calculate (e) {
var bill = document.getElementById('bill'),
tipRatio = e.target.value;
document.getElementById('final-value').textContent = bill.value * (1+tipRatio/100);
}
// append event listeners to each button
for(i = 0; i < max; i++) {
buttons[i].addEventListener('click', calculate, true);
}
EXPLANATIONS
说明
About the HTML, not "much" has changed. The only thing being I'm using something that is a little more standards compliant. I've added a wrapperelement, this is just to isolate some DOM traversal instead of going through the whole document object to do your lookups (this will speed up your script). Your buttons use "value" attribute, which is best. Since you can display button text one way, but use a proper value (see I added % characters). Other than that, I mostly added proper identifiers and labels.
关于 HTML,没有“太多”改变。唯一的事情是我正在使用更符合标准的东西。我添加了一个包装器元素,这只是为了隔离一些 DOM 遍历而不是遍历整个文档对象来进行查找(这将加快您的脚本速度)。您的按钮使用“值”属性,这是最好的。由于您可以以一种方式显示按钮文本,但请使用适当的值(请参阅我添加了 % 字符)。除此之外,我主要添加了适当的标识符和标签。
The JavaScript, this is where i'll go a little more in detail, I'll go step by step:
JavaScript,这是我将更详细地介绍的地方,我将一步一步地进行:
- The first thing you want to do in a script is set the variables you'll need (and fetch the DOM elements you'll be using. This is what I've done on the first 4 lines of code.
- Create a generic function that will handle your calculations and update your elements, no matter their numeric value. The feature I used here is adding a parameter (e) to your function, because EVENTS in javascript attach an EVENT OBJECT to your callback function (in this case
calculate();
). The EVENT OBJECT actually has a bunch of useful properties, of which I use: target: this is the element that triggered the event (i.e. one of your buttons)
- 您想要在脚本中做的第一件事是设置您需要的变量(并获取您将使用的 DOM 元素。这是我在前 4 行代码中所做的。
- 创建一个通用函数来处理您的计算并更新您的元素,无论它们的数值如何。我在这里使用的功能是向您的函数添加参数 (e),因为 javascript 中的 EVENTS 将 EVENT OBJECT 附加到您的回调函数(在本例中
calculate();
)。EVENT OBJECT 实际上有一堆有用的属性,其中我使用: target:这是触发事件的元素(即您的按钮之一)
All we have to do is grab the target's value (e.target.value
) and use that in the math that returns the final bill.
我们所要做的就是获取目标的值 ( e.target.value
) 并在返回最终账单的数学中使用它。
- Using addEventListener. It's generally agreed on that you should keep your JavaScript outside of your HTML, so using the old event methods (onclick="") is discouraged. The
addEventListener()
method isn't too complicated, without going into detail it works as follows:- htmlObject.addEventListener('event type', 'callback function', 'bubbles true/false');
- 使用 addEventListener。人们普遍认为应该将 JavaScript 保留在 HTML 之外,因此不鼓励使用旧的事件方法 (onclick="")。该
addEventListener()
方法是不是太复杂,不细说它的工作原理如下:- htmlObject.addEventListener('事件类型', '回调函数', '冒泡真假');
All I did was loop through all your buttons and append the event lsitener.
我所做的只是遍历所有按钮并附加事件 lsitener。
Closing notes
结语
With this script, you can now add any "buttons" you want, the script will take them all into account and adapt accordingly. Just make sure to set their "value".
使用此脚本,您现在可以添加所需的任何“按钮”,脚本将考虑所有这些并相应地进行调整。只要确保设置它们的“值”。
As I was writing this up a few people gave some quick answers. I can't comment yet (low reputation) so I'll leave my comments here.
在我写这篇文章的时候,一些人给出了一些快速的答案。我还不能发表评论(低声誉)所以我会在这里留下我的评论。
Some of the proposed answers tell you to use innerHTML to fetch the tip value. This is wrong, you are using form fields and should use
element.value
that's what it is made for.Some have even dared to say use the HTML5 data-* attributes. sure, you could. But why would you? HTML and the DOM already provide every necessary tool to accomplish your task WITHOUT the need to polute your HTML with unnecessary attributes. the value="" attribute is meant to be used in forms, it should be used over data-* attribute for field values.
As a general note
innerHTML
is meant to get HTML, not necessarily text or values. There are other methods to get the values you are seeking. In the case of form elements, it'selement.value
, in the case of most other HTML elements, it'selement.textContent
.
一些建议的答案告诉您使用 innerHTML 来获取小费值。这是错误的,您正在使用表单字段,并且应该使用
element.value
它的用途。有些人甚至敢说使用 HTML5 data-* 属性。当然,你可以。但你为什么要这样做?HTML 和 DOM 已经提供了所有必要的工具来完成您的任务,而无需使用不必要的属性污染您的 HTML。value="" 属性旨在用于表单,它应该用于字段值的 data-* 属性。
作为一般说明
innerHTML
是为了获得 HTML,不一定是文本或值。还有其他方法可以获取您正在寻找的值。对于表单元素,它是element.value
,对于大多数其他 HTML 元素,它是element.textContent
.
Hope these explanations help
希望这些解释有帮助
回答by antelove
function tip(o) {
var input = document.querySelector("input[id='bill']");
var total = input.value * o.innerHTML;
document.querySelector("#tip").innerHTML = "$" + total;
}
Total Bill: <input id="bill" type="text">
<button type="button" onclick="tip(this)">15</button>
<button type="button" onclick="tip(this)">18</button>
<button type="button" onclick="tip(this)">20</button>
<div id="tip">You owe...</div>