我的属性数据坐标中有坐标

<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>


因此,我必须从一个数据坐标中获得两个变量

最佳答案

使用.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


.data()

.trim()

更新资料

对于旧的浏览器支持使用

$.trim()代替.trim()

var firstCor = $.trim(cor[0]);
var lastCor = $.trim(cor[1]);


或使用String.prototype.trim polyfill

关于javascript - 将字符串切成两个变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21786298/

10-08 22:36