创建一个包含所选图像值的数组

时间:2014-10-14 22:48:00

标签: javascript jquery

我试图收集所选的图像,获取它们的值,将它们放入一个数组中,然后将它们推送到一个mysql数据库。

这是我目前的代码

$(document).ready(function() {

  var startfind = $("body").find('.on').val();
  var awnsers = $('.on').map(function() {
    return $(startfind).text();
  }).get().join(',');
  $("img").click(function() {
    $(this).toggleClass("on");
  });
  $('button').click(function() {
    alert(awnsers);
  });
});
#seasoning {
  margin: 8px;
  font-size: 16px;
  height: 100px;
  width: 100px;
}
.on {
  padding: 10px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://i.imgur.com/7HyU4yh.jpg" id="seasoning" value="0">
<br>
<img src="https://i.imgur.com/OEHCjCK.jpg" id="seasoning" value="1">
<br>
<button>Submit</button>

我无法获取警报以显示所选项目的值。

2 个答案:

答案 0 :(得分:0)

请检查此代码。

  $("img").on('click',function() {
    $(this).toggleClass("on");
  });
  $(document).on('click', 'button', function() {
        var awnsers = $('.on').map(function() { 
        return  $(this).attr('value');

  }).get().join(','); 
    alert(awnsers);

});

工作小提琴 - http://jsfiddle.net/Ashish_developer/6ezf363a/

答案 1 :(得分:0)

  1. 您可以在单击图像时触发事件
  2. 然后听听那个事件,更新答案
  3. 在需要时使用答案
  4. 我在你的html代码中改变一点,将img的值attr改为数据值

    ============这是代码和jsFiddle =======================

    &#13;
    &#13;
    $(function(){
        //catch this values, because you will use these for more than one time
        var answers = [];
        
        function getAnswers(){
            answers = []; //empty old answers so you can update it
            $.map($('.on'), function(item){
                answers.push($(item).data('value'));
            });
        }
    //init the answers in case you use it before click
    getAnswers();
    
        
        $(document).on('click', 'img', function(e){
            e.preventDefault();
            $(this).toggleClass('on');
            
            //trigger the state change when you click on an image
            $(document).trigger('state-change');
        });
        
        //get answers when event was triggered
        $(document).on('state-change', function(e){
            getAnswers();
        });
        
        $('#btn-show').click(function(){
            alert(answers.join(',') || 'nothing was selected');
        }); 
        
    });
    &#13;
    #seasoning {
      margin: 8px;
      font-size: 16px;
      height: 100px;
      width: 100px;
    }
    .on {
      padding: 10px;
      background-color: red;
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <img src="https://i.imgur.com/7HyU4yh.jpg" id="seasoning" data-value="0">
    <br>
    <img src="https://i.imgur.com/OEHCjCK.jpg" id="seasoning" data-value="1">
    <br>
    
    <button id="btn-show">Submit</button>
    &#13;
    &#13;
    &#13;