我的属性数据坐标
中有坐标<a class="cor" href="#" data-coordinates="37.650621, 55.740887"></a>
我需要将它们分成两个变量,比如
<script>
//this must contain coordinate which is before ","
var firstCor = $('.cor').attr('data-coordinates');
//this must contain coordinate which is after ","
var lastCor = $('.cor').attr('data-coordinates');
</script>
那么,我必须从一个数据坐标中得到两个变量
答案 0 :(得分:2)
使用.split()
var cor = $('.cor').data('coordinates').split(','); // creates an array of result
var firstCor = cor[0].trim(); // access 1st value index starts from 0
var lastCor = cor[1].trim(); //.trim() to remove empty spaces from start and end
<小时/>
更新
对于旧浏览器支持,请使用
var firstCor = $.trim(cor[0]);
var lastCor = $.trim(cor[1]);
答案 1 :(得分:1)
使用.split(),如果要转换为浮动使用parseFloat
var arr = $('.cor').data('coordinates').split(',');
var firstCor = $.trim(arr[0]);
var lastCor = $.trim(arr[1]);
答案 2 :(得分:1)
var co = $('.cor').data('coordinates');
var temp=new Array();
temp=co.split(",");
var firstCor =temp[0];
var lastCor = temp[1];
答案 3 :(得分:1)
另一种方法是使用正则表达式
var cords = $('.cor').data('coordinates').match(/-?\d+\.\d+/g);
导致数组有两个字符串
["37.650621", "55.740887"]
如果要将它们转换为数字,浏览器支持Array map()
var cords = $('.cor')
.data('coordinates')
.match(/-?\d+\.\d+/g)
.map( function(a){ return parseFloat(a); });
导致
[37.650621, 55.740887]