简体   繁体   English

jQuery函数-多个输入/ 1个函数

[英]jquery functions - multiple inputs / 1 function

I have the following 3 actions that essentially check a radio button when a label is clicked. 我有以下3个操作,它们在单击标签时基本上检查了单选按钮。 is there a way to write these as one function as opposed to 3 individual ones? 有没有办法将这些作为一个函数而不是三个单独的函数来编写?

$("input[name='customOrder-qty']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);  
 });

$("input[name='customOrder-price']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);  
 });

$("input[name='customOrder-name']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);  
 });

thank you 谢谢

use selectors separated by commas 使用以逗号分隔的选择器

$("input[name='customOrder-qty'], input[name='customOrder-price'] 
                  ,input[name='customOrder-name'] ").on('click', function() { 
      $('#qtyPackage-custom').prop('checked', true);
});

or better use Attribute contains or starts with selector 或更好地使用属性包含或以选择器开头

$("input[name*='customOrder']").on('click', function() { 
      $('#qtyPackage-custom').prop('checked', true);
});

contains selector - * 包含选择器- *

starts with - ^ 以- ^开头

A few ways you can do it: 有几种方法可以做到:

One is to combine your selectors for the event so that you would have 一种是结合事件的选择器,这样您就可以

$("input[name='customOrder-qty'], input[name='customOrder-price'], input[name='customOrder-name']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);
});

The other is to define the bound code as an actual function, and call the function from each event binding 另一种是将绑定的代码定义为实际函数,并从每个事件绑定中调用该函数

$("input[name='customOrder-qty']").on('click', doStuff);

$("input[name='customOrder-price']").on('click', doStuff);

$("input[name='customOrder-name']").on('click', doStuff);

function doStuff()
{
    $('#qtyPackage-custom').prop('checked', true);
}

Or you can combine both methods to have the following 或者,您可以将两种方法结合使用以实现以下目的

$("input[name='customOrder-qty'], input[name='customOrder-price'], input[name='customOrder-name']").on('click', doStuff);

function doStuff()
{
    $('#qtyPackage-custom').prop('checked', true);
}

Add a common class name to each of the inputs. 为每个输入添加一个通用的类名。 This makes it a lot easier to scale the logic. 这使得扩展逻辑变得容易得多。

HTML 的HTML

<input class="myClass" />

JS JS

$(".myClass").on('click', function() { $('#qtyPackage-custom').prop('checked', true);});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM