简体   繁体   English

使用onclick函数更改变量

[英]change variable with onclick function

I am trying to make a function that will: 我试图做一个功能,将:

  1. run through all of the checkboxes I have checked in the html document 遍历我在html文档中检查过的所有复选框
  2. only allow 'checkboxLimit' to be checked (ie 4 checkboxes out of the 10 can be checked in the document) 仅允许选中“ checkboxLimit”(即可以在文档中选中10个中的4个复选框)
  3. return an array of the id's of the checked checkboxes (which I call cbl) 返回选中复选框的ID的数组(我称为cbl)

Currently, my issue has something to do with the scope of the onclick function. 目前,我的问题与onclick函数的范围有关。

function getCheckboxes(checkboxLimit) {
    // clear cbl
    cbl = ['','','',''];

    // contstuct list of checkbox tags 
    inputs = document.getElementsByTagName('input');
    var checkboxes = [];
    for ( var i = 0 ; i < inputs.length ; i++ ) {
        if (inputs[i].type == 'checkbox') 
        checkboxes.push(inputs[i]);
    }

All of the code above is functional, but the code below is where I run into issues. 上面的所有代码都可以使用,但是下面的代码是我遇到问题的地方。 The function that is executed after 'onclick' works nicely, because if I alert cbl in the function, it works as I like (shown below). 在“ onclick”之后执行的函数运行良好,因为如果我在函数中提醒cbl,它将按我的意愿运行(如下所示)。 However, once cbl is alerted after the 'onclick' function, it is no longer the same. 但是,一旦在“ onclick”功能之后向cbl发出警报,它便不再相同。

    // construct list of checked checkboxes (limited)
    for ( var i = 0 ; i < checkboxes.length ; i++ ) {
        // if any checkbox is clicked
        checkboxes[i].onclick = function() {
            var checkCount = 0;
            // run through each of the checkboxes
            for ( var j = 0 ; j < checkboxes.length ; j++ ) {
                // if index checkbox is checked
                if ( checkboxes[j].checked == true ) {
                    // add to count
                    checkCount++;
                    // if count is above limit, uncheck
                    // otherwise add to list        
                    if ( checkCount > checkboxLimit)
                        this.checked = false;
                    else
                        cbl[checkCount-1] = checkboxes[j].id;
                }
            }
            // alert that displays cbl how I want
            alert(cbl);
        }
        // alert that does not display cbl how I want
        alert(cbl);
    }
}

So is there some way I can get past this scope issue? 那有什么办法可以解决这个范围问题? I would prefer staying away from JQuery, but whatever can get me to have functional code will work at this point. 我宁愿不使用JQuery,但任何可以使我拥有功能代码的方法都可以在此时工作。

Try something more like this: 尝试更多类似这样的方法:

function checkboxValidate(collection, min, max){
  var mn = typeof min === 'undefined' ? 0 : min;
  var mx = typeof max === 'undefined' ? Infinity : max;
  var cb = [], n = 0;
  for(var i=0,l=collection.length; i<l, i++){
    var c = collection[i];
    if(c.type === 'checkbox' && c.checked){
      cb.push(c); n++;
    }
  }
  if(n < mn){
    // somthing.innerHTML = 'Minimum Requirement Failure';
    return false;
  }
  else if(n > mx){
    // somthing.innerHTML = 'Maximum Requirement Failure';
    return false;
  }
  else{
    return cb;
  }
}
anotherElement.onclick = function(){
  var checkedArray = checkboxValidate(document.getElementsByTagName('input'), 0, 3));
  if(checkedArray && checkedArray[0]){
    // checkedArray has each checkbox Element - more properties than just `id`
  }
  else{
    // checkedArray would be false or not have any checked with min 0
  }
}

Adjust as needed. 根据需要进行调整。

A non cross-browser crude sample. 非跨浏览器的原油样品。 Perhaps you can get something from it: 也许您可以从中得到一些东西:

Fiddle 小提琴

function limitCheck(n) {
    var x = [];
    document.addEventListener('click', function(e) {
        var i, t = e.target;
        if (t.type === 'checkbox') {
            if ((i = x.indexOf(t.id)) > -1) {
                console.log('remove ' + i + ', ' + t.id);
                x.splice(i, 1);
            } else if (x.length < n) {
                x.push(t.id);
            } else {
                console.log('LIM');
                e.preventDefault();
                e.stopPropagation();
            }
            console.log(x);
        }
    });
} 

limitCheck(4);

Without debug: 没有调试:

function limitCheck(n) {
    var x = [];
    document.addEventListener('click', function(e) {
        var i, t = e.target;
        if (t.type === 'checkbox') {
            if ((i = x.indexOf(t.id)) > -1) {
                x.splice(i, 1);
            } else if (x.length < n) {
                x.push(t.id);
            } else {
                e.preventDefault();
                e.stopPropagation();
            }
        }
    });
} 

You can put a click listener on an ancestor of the checkboxes, probably they're in a form so use that. 您可以将单击侦听器放置在复选框的祖先上,可能它们是采用表单的形式,因此可以使用它。 You also need to account for a reset button, and for buttons that are checked by default (so you also need to run the function on page load to pre-populate the list): 您还需要考虑一个重置按钮和默认情况下选中的按钮(因此,您还需要在页面加载时运行该功能以预先填充列表):

var checkboxLimit = 4;
var cbl;

function limitCheckboxes(form, event) {

  // Clear checkbox list
  var cblTemp = [];

  // get element that the click came from
  var tgt = event.target || event.srcElement;

  // See if it was a reset
  var reset = tgt.type == 'reset';

  // Count checked checkboxes
  // If click was from reset, reset the checkbox first
  var cb, cbs = form.getElementsByTagName('input');

  for (var i=0, iLen=cbs.length; i<iLen; i++) {
    cb = cbs[i];

    if (cb.type == 'checkbox') {
      cb.checked = reset? cb.defaultChecked : cb.checked;
      if (cb.checked) {
        cblTemp.push(cb.id);
      }
    }
  }

  // If too many, remove the last one that was checked,
  // uncheck it and show a message
  if (cblTemp.length > checkboxLimit && tgt.type == 'checkbox') {
    cblTemp.splice(cblTemp.indexOf(tgt.id), 1);
    tgt.checked = false;
    console.log('removed ' + tgt.id);
  }

  // update cbl
  cbl = cblTemp;

  // Debug
  console.log(cbl);
}

You can also get the checked checkboxes in one go using querySelectorAll : 您还可以使用querySelectorAll一次性获得选中的复选框:

  var cb, cbs = document.querySelectorAll('input[type="checkbox"]');

and the for loop is simpler: for循环更简单:

  for (var i=0, iLen=cbs.length; i<iLen; i++) {
    cb = cbs[i];
    cb.checked = reset? cb.defaultChecked : cb.checked;

    if (cb.checked) {
      cblTemp.push(cb.id);
    }
  }

It would be even better to use a class, so you can have other checkboxes that aren't part of the restricted set. 使用一个类会更好,因此您可以拥有不属于受限集的其他复选框。

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

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