javascript - 使用 javascript 在单击时更改按钮文本/值

标签 javascript html

我的目标是在函数中包含 Element.ID,然后获取它们的值或文本。减少代码行也很重要,因为还有许多其他按钮具有相同的规则。

因此,我尝试了以下代码和许多其他代码以获得适当的结果。

我该如何解决?

var el = document.getElementById("p1");
var id = document.getElementById("p1").id;

el.addEventListener("click", modifyText(id), false);

function modifyText(e) {
  var x = e.value;
  if (x < 40) {
    e.value = 1;
  }
};
<input id="p1" type="button" class="button" value=0>
<input id="pn" type="button" class="button" value=0>

最佳答案

嗯,.addEventListener() 的第二个参数必须是函数引用,而不是要执行的“松散”代码。所以,如果你想调用另一个函数并向它传递一个参数,该行应该是:

el.addEventListener("click", function(){modifyText(id)}, false);

现在,您从元素的 id 中获取了很多信息,但您实际上只需要 id 来获取对该元素的初始引用。一旦你掌握了它,你就可以使用它了。

这里有很多不必要的代码。 另外,我假设(可能是错误的)您希望两个按钮具有相同的click 行为,所以这就是我要进行的操作。

// You only need to get a reference to the element in question
var el1 = document.getElementById("p1");
var el2 = document.getElementById("pn");

// Set up each button to use the same click callback function
// The second argument needs to be a function reference
el1.addEventListener("click", modifyText);
el2.addEventListener("click", modifyText);

function modifyText(){
 // When inside of an event handler, "this" refers to the element
 // that triggered the event.
 if (this.value < 40 ) {
  this.value = 1;
 }
}
<input id = "p1" type="button" class="button" value=0> 
<input id = "pn" type="button" class="button" value=0>

关于javascript - 使用 javascript 在单击时更改按钮文本/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038098/

相关文章:

javascript - KineticJS 如何为图像设置动画

html - 当表没有使用CSS的行时隐藏标题div

javascript - jQuery - 使用 jquery 获取所有内部元素并修改它们的 CSS

c# - 通过 ActiveX 控件在 JavaScript 中启动应用程序时转义路径

javascript - 在 javascript/underscore 中将 3 个数组连接成 1 个数组

javascript - 如何使用数组包含并根据对象的属性检查对象

javascript - IE9 中的 Angular $http 和 Fusion Table

html - 向内容溢出的 flexbox 添加滚动条

html - SVG 不在 linkedin 中显示图像

javascript - 如何获取单元格中嵌入的文本框的值