简体   繁体   English

如何将函数应用于具有相同类的多个元素?

[英]How can I apply a function to multiple elements with the same class?

I have two (or more) buttons with the same class.我有两个(或更多)具有相同类的按钮。 I want to write a function that sets a variable to the clicked button's value, and want to apply this function to all my buttons.我想编写一个将变量设置为单击按钮的值的函数,并希望将此函数应用于我的所有按钮。 I've read post regarding the 'this' keyword ( such as this one ) but it only works if I place the onclick method inline which I don't want to do.我已经阅读了有关“this”关键字的帖子( 例如这个),但只有当我将onclick方法放置在我不想做的内联时它才有效。

Here is a codepen这是一个代码笔

Here is my code:这是我的代码:

<button class='button' type='button' value='X'>Button 1</button>
<button class='button' type='button' value='Y'>Button 2</button>

var button = document.getElementByClass('button');
var value;

function selectValue(clicked_button) {
      value = clicked_button.value;
}

button.onclick = selectValue;

Also, I am not sure but do I need to use a loop to apply the function to every button?另外,我不确定,但我是否需要使用循环将功能应用于每个按钮? Such as:如:

 for(var i = 0; i <= button.length; i++) {
  button[i].onclick = selectValue; 
}
document.querySelectorAll("button")
    .forEach(btn => btn.addEventListener("click", e => selectValue(btn)));
  • The function getElementByClass doesn't exist, use querySelector instead.函数getElementByClass不存在,请改用querySelector
  • Loop over your button elements and add the onclick event.循环您的按钮元素并添加 onclick 事件。

Recommendation: Use addEventListener instead.建议:改用addEventListener

 var buttons = document.querySelectorAll('.button'); var value; function selectValue() { value = this.value; console.log(value); } for (btn of buttons) btn.onclick = selectValue;
 button { width: 70px; height: 40px; }
 <button class='button' type='button' value='X'>Button 1</button> <button class='button' type='button' value='Y'>Button 2</button>

Resources资源

There are several errors in your code:您的代码中有几个错误:

  • There is no getElementByClass function.没有getElementByClass函数。 I don't know how your code runs.我不知道你的代码是如何运行的。 It's called getElementsByClassName .它被称为getElementsByClassName
  • The getElementsByClassName returns a array of elements (2 in your example), so you'll have to loop through it and add the onclick event. getElementsByClassName返回一个元素数组(在您的示例中为 2),因此您必须遍历它并添加onclick事件。
  • To access the current button inside the onclick event handler, use this .要访问onclick事件处理程序中的当前按钮,请使用this You cannot pass whatever parameters you want to the function because its signature is fixed.您不能将所需的任何参数传递给函数,因为它的签名是固定的。 It gets passed a reference to the event itself, not the clicked element, so the name clicked_button is deceiving.它传递了对事件本身的引用,而不是被点击的元素,所以clicked_button这个名字是骗人的。 We usually call that parameter event , or e for short.我们通常称该参数为event ,或简称为e You can access the element using event.target , but using this is just easier.您可以使用event.target访问元素,但使用this更容易。

Try this (I added the console.log line just for demo, but you don't need it):试试这个(我添加了console.log行只是为了演示,但你不需要它):

 var value; var buttons = document.getElementsByClassName('button'); for (var i = 0; i < buttons.length; i++) { buttons[i].onclick = selectValue; } function selectValue() { value = this.value; console.log(value); }
 <button class='button' type='button' value='X'>Button 1</button> <button class='button' type='button' value='Y'>Button 2</button>

Yes you need to use loop over HTMLCollection buttons是的,您需要在 HTMLCollection buttons上使用循环

function selectValue(event) {
  value = event.target.value;
}
var button = document. getElementsByClassName('button');
for (var i = 0; i < button.length; i++) {
  button[i].onclick = selectValue;
}

If using jquery, you use either of the following without looping.如果使用 jquery,您可以使用以下任一方法而无需循环。

  1. This will set value to the clicked button这将为单击的按钮设置值

    var valueToSet = 'XX'; var valueToSet = 'XX';
    $(document).on('click', '.button', function () { $(this).val(valueToSet); }); $(document).on('click', '.button', function () { $(this).val(valueToSet); });

  2. This will set same value for every element with class name button这将为每个具有类名按钮的元素设置相同的值

    var valueToSet = 'XX'; var valueToSet = 'XX';
    $(document).on('click', '.button', function () { $('.button').val(valueToSet); }); $(document).on('click', '.button', function () { $('.button').val(valueToSet); });

  3. Use this in a case where there are other elements with class name button other than the buttons在按钮以外的其他元素具有类名按钮的情况下使用此选项

    var valueToSet = 'XX'; var valueToSet = 'XX'; $("button.button").click(function(){ if($(this).attr("class") == 'button'){ $('button.button').val(valueToSet); } }); $("button.button").click(function(){ if($(this).attr("class") == 'button'){ $('button.button').val(valueToSet); } });

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

相关问题 将jQuery函数应用于具有相同类的多个元素 - Apply jQuery function to multiple elements with same class 如何将 Clamp.js 应用于具有相同类的多个元素? - How can I apply Clamp.js to multiple elements with the same class? 如何将jQuery函数应用于具有相同类的所有元素? - How can I apply a jQuery function to all elements with the same class.? 如何将JavaScript函数应用于同一类下的多个不同元素(结果不同)? - How can I apply JavaScript function to several different elements under the same class (with different results)? 如何同时为多个元素应用悬停事件? - How can I apply hover event for multiple elements at the same time? 如何将 jQuery 函数应用于具有相同 ID 的所有元素? - How can I apply a jQuery function to all elements with the same ID? 如何将我的功能应用于多个元素? - How can i apply my function to multiple elements? jQuery-将函数应用于具有相同类名的多个选择元素 - jQuery - apply function to multiple select elements with same class name 滚动时如何将jQuery shadow函数应用于具有相同类名的多个元素 - How to apply jQuery shadow function to multiple elements with the same class name when scrolled 如何同时将同一功能应用于多个元素? - How to apply same function to multiple elements at the same time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM