复选框图像

时间:2017-08-04 17:57:01

标签: javascript html checkbox

我正在尝试制作一个仅包含图像和

的复选框列表表单

我有来自add an image to a html type input check box or radio的代码:

<html>
<script type="text/javascript">
    //global variables that can be used by ALL the function son this page.
    var inputs;
    var imgFalse = '52 0 ROff.png';
    var imgTrue = '52 0 ROn.png';

    //replace the checkbox with an image and setup events to handle it
    function replaceChecks() {
        //get all the input fields on the page
        inputs = document.getElementsByTagName('input');

        //cycle trough the input fields
        for(var i=0; i<inputs.length; i++) {

            //check if the input is a checkbox
            if(inputs[i].getAttribute('type') == 'checkbox') {

                //create a new image
                var img = document.createElement('img');

                //check if the checkbox is checked
                if(inputs[i].checked) {
                    img.src = imgTrue;
                } else {
                    img.src = imgFalse;
                }

                //set image ID and onclick action
                img.id = 'checkImage'+i;
                //set image
                img.onclick = new Function('checkClick('+i+')');

                //place image in front of the checkbox
                inputs[i].parentNode.insertBefore(img, inputs[i]);

                //hide the checkbox
                inputs[i].style.display='none';
            }
        }
    }

    //change the checkbox status and the replacement image
    function checkClick(i) {
        if(inputs[i].checked) {
            inputs[i].checked = '';
            document.getElementById('checkImage'+i).src=getImageUnchecked(i);
        } else {
            inputs[i].checked = 'checked';
            document.getElementById('checkImage'+i).src=getImageChecked(i);
        }
    }

    function getImageChecked(input) {
        if (input == 0)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
    }

    function getImageUnchecked(input) {
        if (input == 0)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
    }

    function startImages() {

    }

</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>

但是图像只在第一次点击后才开始显示。 我是否可以从页面加载开始做任何工作? 我尝试了现有的功能但没有做任何事情。

2 个答案:

答案 0 :(得分:2)

您已将checkClick()附加到图片的点击事件,但您最初从未实际加载图片,因此您必须从for循环调用checkClick(i)

&#13;
&#13;
<html>
<script type="text/javascript">
    //global variables that can be used by ALL the function son this page.
    var inputs;
    var imgFalse = '52 0 ROff.png';
    var imgTrue = '52 0 ROn.png';

    //replace the checkbox with an image and setup events to handle it
    function replaceChecks() {
        //get all the input fields on the page
        inputs = document.getElementsByTagName('input');

        //cycle trough the input fields
        for(var i=0; i<inputs.length; i++) {

            //check if the input is a checkbox
            if(inputs[i].getAttribute('type') == 'checkbox') {

                //create a new image
                var img = document.createElement('img');

                //check if the checkbox is checked
                if(inputs[i].checked) {
                    img.src = imgTrue;
                } else {
                    img.src = imgFalse;
                }
                //set image ID and onclick action
                img.id = 'checkImage'+i;
                //set image
                img.onclick = new Function('checkClick('+i+')');

                //place image in front of the checkbox
                inputs[i].parentNode.insertBefore(img, inputs[i]);

                //hide the checkbox
                inputs[i].style.display='none';
                checkClick(i);
            }
        }
    }

    //change the checkbox status and the replacement image
    function checkClick(i) {
        if(inputs[i].checked) {
            inputs[i].checked = '';
            document.getElementById('checkImage'+i).src=getImageUnchecked(i);
        } else {
            inputs[i].checked = 'checked';
            document.getElementById('checkImage'+i).src=getImageChecked(i);
        }
    }

    function getImageChecked(input) {
        if (input == 0)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
    }

    function getImageUnchecked(input) {
        if (input == 0)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
    }

    function startImages() {

    }
</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您有大量不必要的代码,并且将初始图像值设置为不存在的图像。

此外,您的HTML无效(<html>结束标记必须是文档中的最后一个内容。

此外,you should not use inline HTML event attributesonclick等)将您的JavaScript与HTML完全分开,并遵循基于标准的现代编码实践。

此外,除非您希望在某些时候(非常不可能)将HTML解析为XML,否则可以省略元素中的最后一个斜杠(<input ... />可以只是<input ... >)。同样,您不再需要在脚本标记中指定type="text/javascript"

以下是代码的清理和现代化工作版本。注意实际上有多少代码(没有注释,它的代码真的很少)以及代码的简单程度。请查看代码中的注释,了解正在执行的操作和原因。

&#13;
&#13;
.hidden { display:none; }
&#13;
<html>
  <head>
    <title>Checkbox and Images</title>
  </head>
  <body>
    <input type="checkbox" id="option1" checked> Test<br>
    <input type="checkbox" id="option2" checked> two<br>
    <button id="btnOutput">Check</button>
  
    <script>
      // You should never make global variables as they can collide with other variables
      // Instead, create a "scope" of your own to work in with an Immediately Invoked
      // function expression (an unnamed function that invokes itself right after being
      // declared)
      (function(){
        // Anything declared inside this function is not accessible outside of it
        
        // Since we know these are the only two image paths needed, we can set them up as
        // variables and completely do away with the extra functions that set them.
        var imgFalse = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
        var imgTrue = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
    
        // Get references to all the DOM elements you will need and then you don't
        // have to scan for them again over and over.
        var btnOutput = document.getElementById("btnOutput");
       
        // .getElementsByTagName() returns a "live node" list that causes the DOM
        // to be re-scanned for the elements everytime you reference the list. 
        // Use .querySelectorAll() for better efficiency and turn the node list that
        // returns into a proper JavaScript array so that .forEach() can be used to
        // iterate the elements later.
        var checkboxes = 
            Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]'));       
            
        // Set up the click event handling function for the button
        btnOutput.addEventListener("click", function(){
          alert('option 1 is checked? ' + checkboxes[0].checked + 
                'option 2 is checked? ' + checkboxes[1].checked);
        });

        // Loop through the checkboxes array
        checkboxes.forEach(function(checkbox, index){
        
          // No need to test the input type because this array only contains checkboxes
          
          // create a new image
          var img = document.createElement('img');

          // Show the right image based on the checked status of the clicked checkbox
          if(checkbox.checked) {
            img.src = imgTrue;
          } else {
            img.src = imgFalse;
          }

          img.id = 'checkImage' + index;   // set image ID
          img.checked = false;
           
          // Set up image click event handler
          img.addEventListener("click", function(){
            
            // Toggle the checked state of the image.
            // In JavaScript, the "checked" property is boolean. It has values of true and false,
            // not "checked" and "" (those are the values to use in HTML attributes).
            this.checked = !this.checked; 
            
            if(this.checked) {
              img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
            } else {
              img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
            }
           
          });

          // place image just prior to the checkbox in the DOM
          checkbox.parentNode.insertBefore(img, checkbox);

          // Hide the checkbox. Use CSS classes instead of inline styles
          checkbox.classList.add("hidden");
        });  
      })();
    
  </script>
</body>
</html>
&#13;
&#13;
&#13;