如何在变更事件中使用无线电?

Ash*_*hta 442 jquery jquery-ui

我有两个单选按钮更改事件我想要更改按钮怎么可能?我的守则

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer
Run Code Online (Sandbox Code Playgroud)

脚本

<script>
    $(document).ready(function () {
        $('input:radio[name=bedStatus]:checked').change(function () {
            if ($("input[name='bedStatus']:checked").val() == 'allot') {
                alert("Allot Thai Gayo Bhai");
            }
            if ($("input[name='bedStatus']:checked").val() == 'transfer') {
                alert("Transfer Thai Gayo");
            }
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

und*_*ned 855

您可以使用thiswhich引用当前input元素.

$('input[type=radio][name=bedStatus]').change(function() {
    if (this.value == 'allot') {
        alert("Allot Thai Gayo Bhai");
    }
    else if (this.value == 'transfer') {
        alert("Transfer Thai Gayo");
    }
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/4gZAT/

请注意,您正在比较allotif语句和:radio选择器中的值.

如果您不使用jQuery,可以使用document.querySelectorAllHTMLElement.addEventListener方法:

var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');

function changeHandler(event) {
   if ( this.value === 'allot' ) {
     console.log('value', 'allot');
   } else if ( this.value === 'transfer' ) {
      console.log('value', 'transfer');
   }  
}

Array.prototype.forEach.call(radios, function(radio) {
   radio.addEventListener('change', changeHandler);
});
Run Code Online (Sandbox Code Playgroud)

  • 问题解决'Thayi gayo bhai'^ _ ^ (36认同)
  • Ala bhai,Ek 数解!:D (8认同)
  • @Piterden首先,这个答案是6岁!ES6中引入了箭头函数,用于您不关心`this`值或者您想在处理程序中使用周围上下文`this`值的情况,此片段使用`this`.声称使用常规功能是"旧的坏习惯"完全没有意义!此外,旧版浏览器不支持箭头函数语法和"Array#includes",并且应该使用transpiler和shim来支持旧浏览器.为什么要做一个与箭头功能无关的简单答案? (5认同)
  • 请注意:我不懂那种语言。 (4认同)
  • [`:radio` 选择器](http://api.jquery.com/radio-selector/) 没有被弃用(在 jQuery 中)。 (2认同)
  • 我使用的是event.target而不是this。 (2认同)

Ohg*_*why 126

适应上述答案......

$('input[type=radio][name=bedStatus]').on('change', function() {
  switch ($(this).val()) {
    case 'allot':
      alert("Allot Thai Gayo Bhai");
      break;
    case 'transfer':
      alert("Transfer Thai Gayo");
      break;
  }
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/xwYx9/

  • @Ohgodwhy - "on"在为事件委托提供上下文时会有所收获,甚至如你所说的那样为动态选择器提供,但是你编写它的方式与上面的答案完全相同. (5认同)
  • @okenshield` .on()`相对于上面的内容确实有所增加,但是,考虑到动态选择器,它肯定是jQuery 1.7+的唯一方法. (3认同)
  • 使用“on”和上面的答案有什么区别? (2认同)

Rag*_*ine 31

更简单,更清洁的方法是使用@ Ohgodwhy答案的课程

<input ... class="rButton">
<input ... class="rButton">
Run Code Online (Sandbox Code Playgroud)

脚本

?$( ".rButton" ).change(function() {
    switch($(this).val()) {
        case 'allot' :
            alert("Allot Thai Gayo Bhai");
            break;
        case 'transfer' :
            alert("Transfer Thai Gayo");
            break;
    }            
});?
Run Code Online (Sandbox Code Playgroud)


bro*_*lio 15

$(document).ready(function () {
    $('#allot').click(function () {
        if ($(this).is(':checked')) {
            alert("Allot Thai Gayo Bhai");
        }
    });

    $('#transfer').click(function () {
        if ($(this).is(':checked')) {
            alert("Transfer Thai Gayo");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

JS小提琴

  • 而不是`$(this).is(":checked")``使用`this.checked`.它是纯粹的JS,因此速度更快. (18认同)
  • @ Gh61,我好奇并且进行了测试.纯JS [快得多](https://jsperf.com/jquery-checked-vs-javascript-checked/1). (6认同)

Sim*_*old 9

简单的ES6 (仅限 JavaScript)解决方案。

document.forms.demo.bedStatus.forEach(radio => {
  radio.addEventListener('change', () => {
    alert(`${document.forms.demo.bedStatus.value} Thai Gayo`);
  })
});
Run Code Online (Sandbox Code Playgroud)
<form name="demo">
  <input type="radio" name="bedStatus" value="Allot" checked>Allot
  <input type="radio" name="bedStatus" value="Transfer">Transfer
</form>
Run Code Online (Sandbox Code Playgroud)


san*_*mar 7

使用onchage功能

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot" onchange="my_function('allot')">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer" onchange="my_function('transfer')">Transfer

<script>
 function my_function(val){
    alert(val);
 }
</script>
Run Code Online (Sandbox Code Playgroud)


Pit*_*den 6

document.addEventListener('DOMContentLoaded', () => {
  const els = document.querySelectorAll('[name="bedStatus"]');

  const capitalize = (str) =>
    `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

  const handler = (e) => alert(
    `${capitalize(e.target.value)} Thai Gayo${e.target.value === 'allot' ? ' Bhai' : ''}`
  );

  els.forEach((el) => {
    el.addEventListener('change', handler);
  });
});
Run Code Online (Sandbox Code Playgroud)


Str*_*ger 5

如果单选按钮是动态添加的,你可能希望使用这个

$(document).on('change', 'input[type=radio][name=bedStatus]', function (event) {
    switch($(this).val()) {
      case 'allot' :
        alert("Allot Thai Gayo Bhai");
        break;
      case 'transfer' :
        alert("Transfer Thai Gayo");
        break;
    }     
});
Run Code Online (Sandbox Code Playgroud)