javascript - 如何从单选按钮设置元素的属性而不提交

标签 javascript jquery html

我有很多按钮。如果我点击其中之一,则调用此函数:

function addOptions(id)
{
  var button = document.getElementById(id); //clicked button
  radioDiv = document.querySelector("div.radioDiv");
  radioDiv.style.visibility = "visible";
  var raz = document.getElementsByName('status'); //get radioButtons
  $(".radioDiv").ready(function() {
    $('input[type=radio][name=status]').change(function(){

         /*Here I'm trying to set attribute to only one button but 
           here the problem: when I click a few buttons (example: 1st then 2nd, then 3rd) 
           and on 3rd button I choice the "radioButton" this code is set Attribute for 
           all of them (3) */

                button.setAttribute("status", this.value);  
            });
          });
        }

enter image description here

这里是index.html。 RadioDiv 默认隐藏

   <div class="layer1">
    <div class="radioDiv">
      <input type="radio" value="sale" name="status">111
      <input type="radio" value="inverted" name="status">222
    </div>
  </div>
  <div class="layer2"></div>

因此,我需要根据 RadioButton 的值设置按钮的属性。

最佳答案

在 js 文件的开头使用全局变量。

var lastButton;
function addOptions(id) {
  $(".radioDiv input[type=radio][name=status]").prop("checked", false);
  lastButton = document.getElementById(id); //last clicked button
  var status = lastButton.getAttribute("status");
  $(".radioDiv input[type=radio][name=status][value='" + status +"']").prop("checked", true);
  $(".radioDiv").prop("visible", true);
  $('input[type=radio][name=status]').click(function(){
    lastButton.setAttribute("status", this.value);
  });
}

关于javascript - 如何从单选按钮设置元素的属性而不提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40802140/

相关文章:

javascript - 如何根据父 div 不同地检查复选框?

javascript - 什么时候应该使用 var 函数和 when 函数

javascript - ajax提交上传进度总是返回100

javascript - 在加载和调整大小时将 javascript 函数的结果调用到 Jquery css 事件中

css - 在 Bootstrap 下拉菜单中面临问题,例如最后一个选项中的边框切割

javascript - 类型错误 : Cannot read property 'then' of undefined #2

javascript - 如何在 native react 中显示两个 Firestore 集合中的数据

javascript - ionic : how to use cssClass in $ionicPopup?

javascript - 将 javascript 对象完整传递给 ruby​​ 类

jquery - 单击元素时交叉淡入淡出文本而不跳下