I have a problem with the split()
function.
I get the error undefined but it dont know why :/
It is easier to explain with a working example: http://www.jsfiddle.net/V9Euk/415/
$(function start()
{
css('#div { font-color:#ff0000; border:1px solid #00ff00; }', '#div_2 { font-color:#ff0000; }', '#line2 { font-color:#00ffff; }');
});
function css(c0,c1,c2)
{
if(c0 != 'undefined')
{
c0_selector = c0.match(/^.*{/);
c0 = c0.replace(/^.*{/,'');
c0 = c0.replace(/}/,'');
c0_arr = c0.split(';');
values = new Array();
values[0] = new Array();
values[0][0] = c0_selector;
for (i = 1; i < c0_arr.length; i++)
{
values[0][i]= c0_arr[i].split(':');
}
}
if(c1 != 'undefined')
{
c1_selector = c1.match(/^.*{/);
c1 = c1.replace(/^.*{/,'');
c1 = c1.replace(/}/,'');
c1_arr = c1.split(';');
values[1] = ne开发者_开发百科w Array();
values[1][0] = c1_selector;
for (i = 1; i < c1_arr.length; i++)
{
values[1][i]= c1_arr[i].split(':');
}
}
$('#log').append(''+values[0][0]+'<br />');
$('#log').append(''+values[0][1][0]+'<br />');
$('#log').append(''+values[0][1][1]+'<br />');
$('#log').append('<hr />');
$('#log').append(''+values[1][0]+'<br />');
$('#log').append(''+values[1][1][0]+'<br />');
$('#log').append(''+values[1][1][1]+'<br />');
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'json',
data: $.toJSON(values),
contentType: 'application/json; charset=utf-8',
success: function() {
alert('success');
}
});
}
Thanks in advance! Peter
Your for loops are wrong.
c0_arr = c0.split(';');
You get indexes 0 and 1 containing stuff after that.
And then you loop like this:
for (i = 1; i < c0_arr.length; i++)
{
values[0][i]= c0_arr[i].split(':');
}
Starting at index 1. You should start at index 0, and fill your values array like this:
for (i = 0; i < c0_arr.length; i++)
{
values[0][i+1]= c0_arr[i].split(':');
}
Then you will get all your values where they belong.
Previous answer explains clearly why you get the undefined error BTW.
You already have the lines logging your values array, was it so hard to add lines logging the other vars?
c1_arr = c1.split(';');
The array created here is ['font-color:#ff0000', ''] - there is a blank second element since there's nothing after the ';' in the input string.
Then when you call:
values[1][i]= c1_arr[i].split(':');
c1_arr[1] is empty string, so values[1][1] is an array with only one element, empty string.
values[1][1][0] -> empty string values[1][1][1] -> undefined (no second element)
精彩评论