jquery/javascript: arrays

一笑奈何 提交于 2019-12-11 04:27:30

问题


I am a begginer with Javascript/jQuery and I hope someone can help me with the following:

I have a simple form (7 questions; 3 radio buttons/answers per question - except for question 5 with 8 possible choices ) and based on the selected answers, when user clicks on 'view-advice' I want to display relevant advices (combination of 38 possible advices) below the form. I have given "a", "b", "c",... values to radio buttons and I am collecting them in an array. The part where the script alerts the array works ok. I can't figure out the part where I display the advices depending on the values in the array.

I'd appreciate your help! Thanks!

Here is the code:


var laArray = new Array();

$('.button-show-advice').click(function(){

    $(":radio:checked").each(function(i){
        laArray[i] = $(this).val();
        if (laArray == ["a","d","g","j","m","u"]) {
        $("#advice-container, #advice1, #advice2").show(); // something is wrong here :(
            };
    })
    alert(laArray) // testing to see if it works

})


回答1:


Rather than test for equality, I think the better means is to check whether or not each of your values are in the array using the jQuery inArray function.

Granted, this is just the beginning of code. You could probably write a function to shore this up, like so.

function radioSelected(val) {
  return ($.inArray(val, laArray) != -1);
}

and adapt it to your existing script.




回答2:


You cannot compare arrays this way you should probably either compare each element of the 2 arrays

function compare_array(array1,array2) {
    var i;
    for(i=0;i=array1.length;i++) {
        if(array1[i]==array2[i]) {
            return false;
        }
    }
    return true;
}

or serialize the array in a comparable form ( comma separated string for example )

function compare_array(array1,array2) {
     return array1.join(",")==array2.join(",");
}



回答3:


Would be nice to see the HTML code. But I guess you want to do something like this:


var laArray = [];
var compareValues = function(arr1, arr2) {
  $(arr1).each(function(index, el) {
   if(el !== arr2[index]) {
     return false;
   }
  });
  return true;
};

$('.button-show-advice').click(function(){
    $(":radio:checked").each(function(i){
        laArray.push($(this).val());        
    });
   if(compareValues(laArray,["a","d","g","j","m","u"])) {
      $("#advice-container, #advice1, #advice2").show();
   }  
});

EDIT: updated the code, forgot the }); ...



来源:https://stackoverflow.com/questions/3969576/jquery-javascript-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!